Skip to content

Instantly share code, notes, and snippets.

@Fishrock123
Forked from jlongster/testgen.js
Last active December 18, 2015 05:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fishrock123/5733594 to your computer and use it in GitHub Desktop.
Save Fishrock123/5733594 to your computer and use it in GitHub Desktop.
basic generator async lib fleshed out to be slightly nicer
// based off of https://gist.github.com/creationix/5544019
// these could probably be condensed more, but I'm just doing this
// quickly
exports = module.exports = run;
exports.call = call;
exports.invoke = invoke;
exports.bind = bind;
function call(func) {
var args = Array.prototype.slice.call(arguments, 1);
return function(callback) {
args.push(callback);
func.apply(null, args);
};
}
function invoke(obj, method) {
var args = Array.prototype.slice.call(arguments, 1);
return function(callback) {
args.push(callback);
obj[method].apply(obj, args);
};
}
function bind(func, obj) {
return function() {
var args = Array.prototype.slice.call(arguments);
return function(callback) {
args.push(callback);
func.apply(obj, args);
};
};
}
function run(makeGenerator) {
return function () {
var generator = makeGenerator.apply(this, arguments);
var continuable, sync, value;
next();
function next() {
while (!(continuable = generator.send(value)).done) {
continuable = continuable.value;
sync = undefined;
continuable(callback);
if (sync === undefined) {
sync = false;
break;
}
}
}
function callback(err, val) {
if (err) return generator.throw(err);
value = val;
if (sync === undefined) {
sync = true;
}
else {
next();
}
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment