Created
August 23, 2017 05:32
-
-
Save jackhftang/badad8cc842fbe5097c69401c784d389 to your computer and use it in GitHub Desktop.
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
// 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