Skip to content

Instantly share code, notes, and snippets.

@jlongster
Created June 7, 2013 04:25
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jlongster/5727062 to your computer and use it in GitHub Desktop.
Save jlongster/5727062 to your computer and use it in GitHub Desktop.
basic generator async lib
// based off of https://gist.github.com/creationix/5544019
// these could probably be condensed more, but I'm just doing this
// quickly
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();
}
}
};
};
module.exports = {
run: run,
call: call,
invoke: invoke,
bind: bind
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment