Last active
June 11, 2019 22:29
-
-
Save copperwall/9199837c7b8f0d67329f4016a078a214 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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