Skip to content

Instantly share code, notes, and snippets.

@samoshkin
Created January 15, 2018 20:02
Show Gist options
  • Save samoshkin/b5d30068087f2f303f5447a6ecead361 to your computer and use it in GitHub Desktop.
Save samoshkin/b5d30068087f2f303f5447a6ecead361 to your computer and use it in GitHub Desktop.
Simple "generator + promise" runner routine. Write sync - execute async.
function r(genFn, context){
return function(...args){
const iter = genFn.apply(context || this, args);
return traverse(iter);
}
function traverse(iter){
return new Promise((res, rej) => {
function step(err, arg) {
let value, done;
try {
({ value, done } = err ? iter.throw(err) : iter.next(arg));
} catch(e){
rej(e);
}
if (done) {
res(value);
return;
}
Promise.resolve(value).then(
res => step(null, res),
rej => step(rej));
}
step();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment