Created
March 12, 2017 19:26
-
-
Save mightyguava/debc59219f9ad35efa82c3a6ebcefb0c to your computer and use it in GitHub Desktop.
Demystifying Async Programming in Javascript - co() error solution
This file contains 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
function co(generator) { | |
return new Promise((resolve, reject) => { | |
const g = generator(); | |
function onResolve(value) { | |
let ret; | |
try { | |
ret = g.next(value); | |
} catch (e) { | |
reject(e) | |
return; | |
} | |
next(ret); | |
} | |
function onReject(err) { | |
let ret; | |
try { | |
ret = g.throw(err); | |
} catch (e) { | |
reject(e); | |
return; | |
} | |
next(ret); | |
} | |
function next(ret) { | |
if (ret.done) { | |
return resolve(ret.value); | |
} | |
ret.value.then(onResolve, onReject); | |
} | |
onResolve(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment