I\'m trying to find a good pattern to execute a bunch of parallel tasks.
Let me define some task to exemplify. Tasks a, b, c, d, e, f, g
execute as
yeah, look at flow control module, like step, chain, or flow ~ and i think there is something like that in underscore.js too
Try to look at step module and this article.
You should check out Step ( https://github.com/creationix/step ). It's just over a hundred lines of code, so you can read the whole thing if needed.
My preferred pattern looks something like this:
function doABunchOfCrazyAsyncStuff() {
Step (
function stepA() {
a(arg1, arg2, arg3, this); // this is the callback, defined by Step
}
,function stepB(err, data) {
if(err) throw err; // causes error to percolate to the next step, all the way to the end. same as calling "this(err, null); return;"
b(data, arg2, arg3, this);
}
,function stepC(err, data) {
if(err) throw err;
c(data, arg2, arg3, this);
}
,function stepDEF(err, data) {
if(err) throw err;
d(data, this.parallel());
e(data, this.parallel());
f(data, this.parallel());
}
,function stepGGG(err, dataD, dataE, dataF) {
if(err) throw err;
var combined = magick(dataD, dataE, dataF);
var group = this.group(); // group() is how you get Step to merge multiple results into an array
_.map(combined, function (element) {
g(element, group());
});
}
,function stepPostprocess(err, results) {
if(err) throw err;
var processed = _.map(results, magick);
return processed; // return is a convenient alternative to calling "this(null, result)"
}
,cb // finally, the callback gets (err, result) from the previous function, and we are done
);
}
Notes
What you actually want is a deferred pattern though like futures.
function defer(f) {
// create a promise.
var promise = Futures.promise();
f(function(err, data) {
if (err) {
// break it
promise.smash(err);
} else {
// fulfill it
promise.fulfill(data);
}
});
return promise;
}
var da = defer(a), db = defer(b), dc = defer(c), dd = defer(d), de = defer(e), df = defer(f), dg = defer(g);
// when a and b are fulfilled then call ab
// ab takes one parameter [ra, rb]
Futures.join(da, db).when(ab);
Futures.join(db, dc).when(bc);
// abc takes one parameter [ra, rb, rc]
Futures.join(da, db, dc).when(abc);
Futures.join(db, dd).when(bd);
Futures.join(db, dc, dd).when(bcd);
Futures.join(da, df).when(af);
// where's e ?
Futures.join(df,dg).when(fg);
Futures.join(da,db,dc,dd,de,df,dg).fail(function() {
console.log(":(");
});
nimble is another good choice.
A very simple barrier just for this: https://github.com/berb/node-barrierpoints