Created
December 6, 2015 17:30
-
-
Save dtothefp/2d8987cb02e4f77d7b48 to your computer and use it in GitHub Desktop.
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
/** | |
* Create a `spawn` function to deal with promises | |
* http://blog.mgechev.com/2014/12/21/handling-asynchronous-calls-with-es6-javascript-generators/ | |
*/ | |
function spawn(gen) { | |
const it = gen(); //instantiate the generator and return the generator object | |
function _co(method, arg) { | |
let res; | |
try { | |
//retrieve the promise returned by the http request if `arg` is undefined | |
//if `arg` is defined it will be the data from the http request promise | |
//and will be "injected" into `yield` and caught in a variable | |
res = it[method](arg); | |
} catch(err) { | |
//not sure about the error handling here?? | |
return Promise.reject(err); | |
} | |
if (res.done) { | |
if (method === 'throw') { | |
return arg; | |
} else { | |
return res.value; | |
} | |
} else { | |
//at this point we may resolve a promise or a value?? | |
//a) if we are resolving a promise we will inject it's value by calling `.next` | |
//b) if we are resolving a value it will be ignored by `.next` as `yield` will be | |
// the returned Promise from the http request | |
return Promise.resolve(res.value) | |
.then((val) => { | |
return _co('next', val); | |
}, (err) => { | |
//not sure about the error handling here?? | |
return _co('throw', err); | |
}); | |
} | |
} | |
return _co('next'); //start the process by calling `.next` on the generator instance | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment