Created
March 7, 2017 23:54
-
-
Save creationix/a9ca44efe8757b74dc72a37d82da3c2d to your computer and use it in GitHub Desktop.
Promise version of gen-run.
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 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