Skip to content

Instantly share code, notes, and snippets.

@kjendrzyca
Last active May 3, 2016 17: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 kjendrzyca/28b3f7b1ec765a677fda234b392ebed8 to your computer and use it in GitHub Desktop.
Save kjendrzyca/28b3f7b1ec765a677fda234b392ebed8 to your computer and use it in GitHub Desktop.
function async(genFunc) {
const genObj = genFunc();
const firstNext = genObj.next()
log(firstNext)
step(firstNext);
function step({value,done}) {
if (!done) {
// A Promise was yielded
value
.then(result => {
const secondNext = genObj.next(result)
log(secondNext)
step(secondNext)
})
.catch(error => {
step(genObj.throw(error));
});
}
}
}
var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = new Promise(function(resolve, reject) {
setTimeout(() => {resolve('foo')}, 1000);
});
async(function* () {
try {
// yield == await
const [val1, val2, val3] = yield Promise.all([
p1,p2,p3
]);
log(val1);
log(val2);
log(val3);
} catch (e) {
log('Failure to read: ' + e);
}
});
function log (something) {
console.log(something);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment