Skip to content

Instantly share code, notes, and snippets.

@creationix
Created March 7, 2017 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creationix/a9ca44efe8757b74dc72a37d82da3c2d to your computer and use it in GitHub Desktop.
Save creationix/a9ca44efe8757b74dc72a37d82da3c2d to your computer and use it in GitHub Desktop.
Promise version of gen-run.
function run(iterator) {
return new Promise((resolve, reject) => {
var error, value, done;
next();
function next() {
while (!done) {
// Call into generator, forwarding any thrown errors to the callback.
var evt;
try {
if (error) {
evt = iterator.throw(error);
} else {
evt = iterator.next(value);
}
} catch (err) {
return reject(err);
}
// Record the result from the generator
error = null;
done = evt.done;
value = evt.value;
// If it's a promise, wait for it.
if (typeof value === 'object' &&
typeof value.then === 'function') {
return value.then(onResolve).catch(onReject);
}
}
return resolve(value);
}
function onReject(err) {
error = err;
return next();
}
function onResolve(val) {
value = val;
return next();
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment