是什么async.waterfall和async.series之间的区别

问题描述 投票:106回答:4

在异步的NodeJS模块:https://github.com/caolan/async提供2种类似的方法,async.waterfallasync.series

它们之间有什么区别?

javascript node.js asynchronous node-async
4个回答
162
投票

看来,async.waterfall允许每个函数传递到下一个函数的结果,而async.series通过了所有成果最终回调。在一个更高的水平,async.waterfall将是一个数据管道(“给出2,乘以3它,由17加2,并除以”),而async.series将是必须在顺序执行的离散的任务,但在其他方面分开。


51
投票

做会调用主回调,传递它的错误,如果错误发生时,这两个函数传递的返回值,每一个功能的下一个,然后。

所不同的是async.series(),一旦系列完成后,将通过所有的结果,主要的回调。 async.waterfall()将传递给主回调称为最后一个函数的唯一结果。


26
投票

async.waterfall()正在处理的action that relies on the previous outcome

async.series()正在处理的是要see all the result at the end动作


1
投票

我认为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 - 回调。所有其余的应该接受两个参数 - 值和回调。坚持模式,你会保持理智!

© www.soinside.com 2019 - 2024. All rights reserved.