Skip to content

Instantly share code, notes, and snippets.

@jakearchibald
Last active June 28, 2022 07:33
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save jakearchibald/edbc78f73f7df4f7f3182b3c7e522d25 to your computer and use it in GitHub Desktop.
Save jakearchibald/edbc78f73f7df4f7f3182b3c7e522d25 to your computer and use it in GitHub Desktop.
function createAsyncFunction(fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
}
}
return step("next");
});
};
}
@onildof
Copy link

onildof commented Jun 26, 2022

Hello Jake!

I don't even know how I got to this function (I've got dozens of tabs open while I research asynchronous javascript). At first I found it quite cryptic, but I took figuring it out as a challenge.

So after a few days tinkering with it I believe It takes a generator function, then returns a function that accepts arguments that might be used by such generator function to craft an Iterable. Then it creates said iterable (as a generator object), then returns a pending promise that will start an iteration sequence and only settle when an iteration throws an error, returns a rejected promise, or is the last one.

Now here's the motivation for this comment: I believe the return statements on lines 23 and 16 are both unnecessary/inert. The reasoning being:

For line 23:

  • the returned value of a Promise constructor's executor function is always ignored;
  • the only purpose of such a return statement in an executor function is flow control (preventing subsequent code from executing), as you do on line 11.

For line 16:

  • it's flattening a chain of promises (that started with the first call to step on line 23). Each of the promises entering a handler function with a call to step in the microtask queue. There's no point in chaining those promises, is there? Since in the end the resulting promise will be returned in line 23 (and ignored).

TL;DR: For didactic purposes I removed the return statements in lines 16 & 23, kept the returned expressions. Code worked the same.

I don't even think you'll be bothered with this, but still serves me as an exercise, though.

Loved your event loop talk in JSConf.Asia!

Cheers

@onildof
Copy link

onildof commented Jun 27, 2022

So it's a polyfill from Babel, nevermind then.

@jakearchibald
Copy link
Author

Yep!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment