gui*_* 桂林 5 javascript parallel-processing concurrency design-patterns node.js
我正在努力找到一个好的模式来执行一堆并行任务.
让我来定义一些例子.任务a, b, c, d, e, f, g执行的a(function(er, ra){//task a returned, ra is result}),这样做b对g
也有一些工作,应该是执行一些任务完成后,让我们给他们打电话ab, bc, abc, bd, bcd, af, fg,表示当a和b返回ab(ra, rb)应立即执行,而当b和c退换,bc(rb, rc)应立即执行,如果a,b,c全部返还,abc(ra, rb, rc)应执行.
对于最简单的情况,如果只有a和b,我可以做这样的事情:
(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);
});
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,a和b并行执行者,都完成后,ab(ra, rb)执行.
但是,我如何为许多并行任务做更多的事情呢?
Ray*_*nos 14
你真正想要的是延期模式,虽然像期货一样.
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(":(");
});
Run Code Online (Sandbox Code Playgroud)
你应该看看Step(https://github.com/creationix/step).这只是一百多行代码,所以你可以根据需要阅读整个代码.
我喜欢的模式看起来像这样:
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
);
}
Run Code Online (Sandbox Code Playgroud)
笔记