Skip to content

Instantly share code, notes, and snippets.

@jackhftang
Created August 23, 2017 05:32
Show Gist options
  • Save jackhftang/badad8cc842fbe5097c69401c784d389 to your computer and use it in GitHub Desktop.
Save jackhftang/badad8cc842fbe5097c69401c784d389 to your computer and use it in GitHub Desktop.
// coroutine for callback
function coroutineC(gen, handler) {
let cb = function (err, value) {
switch (err) {
case undefined:
case null:
process.nextTick(function () {
try {
g.next(value)
} catch (ex) {
cb(ex);
}
});
break;
default:
if (typeof handler === 'function') handler(err);
else throw err;
}
};
let g = gen(cb);
cb();
}
// coroutine for promise
function coroutineP(gen) {
return new Promise(function (resolve, reject) {
const g = gen();
const reply = function (res) {
let x;
try {
// x.value :: Promise
x = g.next(res);
} catch (ex) {
reject(ex);
return;
}
if (x.done) resolve(x.value);
else x.value.then(reply).catch(reject);
};
reply();
})
}
module.exports = { coroutineC, coroutineP };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment