Last active
January 8, 2019 22:18
-
-
Save goldhand/ae706adc5441fc87c5625f5c13a1190b to your computer and use it in GitHub Desktop.
Use a generator to make async stuff look sync.
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
/** | |
* Turns generators into async demons | |
* | |
* Within the generator function, any "yield" operator becomes enhanced with async powers | |
* allowing them to yield promises. | |
* | |
* @example | |
* spawn(function *() { | |
* const data = yield fetch('/foo.json'); // will be resolved and assigned to "data" var | |
* console.log(data); // write like its sync but its acually async ;) | |
* }); | |
* | |
* @param {generator} generatorFn - generator function that will be wrapped | |
* @returns {Promise} | |
*/ | |
export default function spawn(generatorFn) { | |
let generator = generatorFn(); | |
let onFulfilled = arg => continuer('next', arg); | |
let onRejected = arg => continuer('throw', arg); | |
function continuer(verb, arg) { | |
let result; | |
try { | |
result = generator[verb](arg); | |
} catch (err) { | |
return Promise.reject(err); | |
} | |
if (result.done) { | |
return result.value; | |
} else { | |
return Promise.resolve(result.value).then(onFulfilled, onRejected); | |
} | |
} | |
return onFulfilled(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explanation: