-
-
Save getify/a6e1bb21a4b1a731e2d2bfbdc6be59bb to your computer and use it in GitHub Desktop.
Exploring how a gen-runner works... using a recursive promise chain
This file contains hidden or 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
// 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); | |
} ); | |
} |
This file contains hidden or 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
// 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); | |
} ); | |
} |
This file contains hidden or 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
// ... 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