Skip to content

Instantly share code, notes, and snippets.

@copperwall
Last active June 11, 2019 22:29
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 copperwall/9199837c7b8f0d67329f4016a078a214 to your computer and use it in GitHub Desktop.
Save copperwall/9199837c7b8f0d67329f4016a078a214 to your computer and use it in GitHub Desktop.
function runner(gen, ...args) {
// Initialize the generator.
let iterator = gen(...args);
// handleNext is responsible for restarting the generator with new input.
return Promise.resolve().then(function handleNext(value) {
// next can be a promise or a sync value.
let next = iterator.next(value);
// handleResult is responsible for taking the output of the generator
// and scheduling handleNext to run once it resolves.
return (function handleResult(next) {
if (next.done)
return next.value;
return Promise.resolve(next.value).then(
handleNext,
function error(err) {
return Promise.resolve(iterator.throw(err)).then(handleResult);
});
})(next);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment