Skip to content

Instantly share code, notes, and snippets.

@ziwon
Created November 10, 2013 16:54
Show Gist options
  • Save ziwon/7400704 to your computer and use it in GitHub Desktop.
Save ziwon/7400704 to your computer and use it in GitHub Desktop.
How to build a chain to manage all subsequent tasks? If we have a set of N tasks in some cases, then we should call `then(fn)` N -1 times, right?
TaskBuilder.prototype.falldown = function(func, handler) {
var self = this;
Q.fcall(func).then(function(cb) {
return function(next) {
cb(function(fn, args) {
fn(args, next);
});
};
}).then(function(cb) {
return function(next) {
cb(function() {
if(_.isFunction(arguments[0])) {
var fn = arguments[0];
fn(arguments[1], next);
} else {
self.send(handler, arguments[0]);
}
});
};
}).then(function(cb) {
cb(function() {
self.send(handler, arguments[0]);
});
}).done();
};
TaskBuilder.prototype.send = function(f, args, cb) {
this.stack.push(args);
if (this.stack.length == this.nodes.length) {
f({
status: 'ok',
nodes: this.stack
});
if(cb) cb();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment