在异步的NodeJS模块:https://github.com/caolan/async提供2种类似的方法,async.waterfall
和async.series
。
它们之间有什么区别?
看来,async.waterfall
允许每个函数传递到下一个函数的结果,而async.series
通过了所有成果最终回调。在一个更高的水平,async.waterfall
将是一个数据管道(“给出2,乘以3它,由17加2,并除以”),而async.series
将是必须在顺序执行的离散的任务,但在其他方面分开。
做会调用主回调,传递它的错误,如果错误发生时,这两个函数传递的返回值,每一个功能的下一个,然后。
所不同的是async.series()
,一旦系列完成后,将通过所有的结果,主要的回调。 async.waterfall()
将传递给主回调称为最后一个函数的唯一结果。
async.waterfall()
正在处理的action that relies on the previous outcome
。
async.series()
正在处理的是要see all the result at the end
动作
我认为async.waterfall是有害的,因为它很难重构写一次,也容易出错,因为如果你提供更多的参数,其它功能太多更改签名。
我强烈建议async.autoInject
作为一个伟大的选择,以async.waterfall。 https://caolan.github.io/async/autoInject.js.html
如果你选择使用async.waterfall,我建议在一个对象存储的一切,所以你的函数没有改变长/签名,就像这样:
警告:这是个坏模式
async.waterfall([
cb => {
cb(null, "one", "two");
},
(one, two, cb) => {
cb(null, 1, 2, 3, 4);
},
(one,two,three,four,cb) => {
// ...
}
])
不这样做上述方式。这是一个更好的模式来使用:
async.waterfall([
cb => {
cb(null, {one:"one", two:"two"});
},
(v, cb) => {
cb(null, [1, 2, 3, 4]);
},
(v,cb) => {
// ...
}
])
这样你不会拉你的头发,试图确保函数的参数有合适的长度。第一个函数只接受一个ARG - 回调。所有其余的应该接受两个参数 - 值和回调。坚持模式,你会保持理智!