Last active
October 14, 2015 03:34
-
-
Save RSNara/148198e78474983d5ecc to your computer and use it in GitHub Desktop.
Use generators with promises for better error handling. :)
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
/* | |
Let `a` be a Promise. To make the generator wait for a to resolve, | |
simply `yield a`. By default, all rejected Promises throw an error | |
in our generator. Yield an iteratable to get an array of resolved | |
values. | |
*/ | |
function isIterable(object) { | |
return Symbol.iterator in Object(object); | |
} | |
function run(generator, ...args) { | |
let iterator = generator(...args); | |
next(iterator.next(), iterator); | |
} | |
function next({value, done}, iterator) { | |
if (done) return; | |
const method = isIterable(value) ? 'all' : 'resolve'; | |
Promise[method](value) | |
.then((result) => { | |
next(iterator.next(result), iterator); | |
}) | |
.catch((error) => { | |
iterator.throw(error); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment