Skip to content

Instantly share code, notes, and snippets.

@mightyguava
Created March 12, 2017 19:26
Show Gist options
  • Save mightyguava/debc59219f9ad35efa82c3a6ebcefb0c to your computer and use it in GitHub Desktop.
Save mightyguava/debc59219f9ad35efa82c3a6ebcefb0c to your computer and use it in GitHub Desktop.
Demystifying Async Programming in Javascript - co() error solution
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