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 a(function(er, ra){//task a returned, ra is result})
, so do b
to g
There are also some tasks that should be execute after some task is done, let's call them ab, bc, abc, bd, bcd, af, fg
, means when a
and b
has returned ab(ra, rb)
should be executed at once, and when b
and c
returned, bc(rb, rc)
should be executed at once, and if a
, b
, c
all returned, abc(ra, rb, rc)
should be executed.
For the simplest case, if there is only a
and b
, I can do something like this:
(function(cb){
var count = 2, _ra, _rb;
function update(){if(--count == 0) cb(null, _ra, _rb)}
a(function(er, ra){_ra = ra; update()});
b(function(er, ra){_rb = rb; update()});
})(function(er, ra, rb){
ab(ra, rb);
});
As you can see, a
and b
execute in parallel, and when both are done, ab(ra, rb)
execute.
But how can I do more things for a lot of parallel tasks?
yeah, look at flow control module, like step, chain, or flow ~ and i think there is something like that in underscore.js too
nimble is another good choice.
What you actually want is a deferred pattern though like futures.
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:
Notes
Try to look at step module and this article.
A very simple barrier just for this: https://github.com/berb/node-barrierpoints