Skip to content

Instantly share code, notes, and snippets.

@getify
Last active June 17, 2016 16:37
Show Gist options
  • Save getify/a6e1bb21a4b1a731e2d2bfbdc6be59bb to your computer and use it in GitHub Desktop.
Save getify/a6e1bb21a4b1a731e2d2bfbdc6be59bb to your computer and use it in GitHub Desktop.
Exploring how a gen-runner works... using a recursive promise chain
// commented `run(..)`:
function run(it) {
// return a promise for the generator completing
return Promise.resolve()
.then( function handleNext(value){
// run to the next yielded value
var next = it.next( value );
return (function handleResult(next){
// generator has completed running?
if (next.done) {
return next.value;
}
// otherwise keep going
else {
return Promise.resolve( next.value )
.then(
// resume the async loop on
// success, sending the resolved
// value back into the generator
handleNext,
// if `value` is a rejected
// promise, propagate error back
// into the generator for its own
// error handling
function handleErr(err) {
return Promise.resolve(
it.throw( err )
)
.then( handleResult );
}
);
}
})(next);
} );
}
// un-commented `run(..)`:
function run(it) {
return Promise.resolve()
.then( function handleNext(value){
var next = it.next( value );
return (function handleResult(next){
if (next.done) {
return next.value;
}
else {
return Promise.resolve( next.value )
.then(
handleNext,
function handleErr(err) {
return Promise.resolve(
it.throw( err )
)
.then( handleResult );
}
);
}
})(next);
} );
}
// ... with some ES6 sugar
function run(it) {
return Promise.resolve()
.then( function handleNext(value){
var next = it.next( value );
return (function handleResult(next){
return next.done ? next.value :
Promise.resolve( next.value )
.then(
handleNext,
err =>
Promise.resolve(
it.throw( err )
)
.then( handleResult )
);
}
})( next );
} );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment