difference between async.series and async.parallel
async.series和async.parallel有什么区别。 考虑下面的例子,我得到了相同的结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | async.parallel([ function(callback){ setTimeout(function(){ callback(null, 'one'); }, 200); }, function(callback){ setTimeout(function(){ callback(null, 'two'); }, 100); }, function(callback){ setTimeout(function(){ var err = new Error('I am the error'); callback(err); }, 400); }, function(callback){ setTimeout(function(){ callback(null, 'three'); }, 600); }, ], // optional callback function(err, results){ if(err){ console.log('Error'); } else { } console.log(results); //results is now equal to [ 'one', 'two', undefined ] // the second function had a shorter timeout. }); |
和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | async.series([ function(callback){ setTimeout(function(){ callback(null, 'one'); }, 200); }, function(callback){ setTimeout(function(){ callback(null, 'two'); }, 100); }, function(callback){ setTimeout(function(){ var err = new Error('I am the error'); callback(err); }, 400); }, function(callback){ setTimeout(function(){ callback(null, 'three'); }, 600); } ], // optional callback function(err, results){ //results is now equal to [ 'one', 'two', undefined ] if(err){ console.log('Error'); } else { } console.log(results); }); |
我看不出有什么区别。 也许我的样品不好? 我在github异步存储库上阅读了关于这两个函数的文档,您可以找到async.parallel函数:
If any of the functions pass an error to its callback, the main
callback is immediately called with the value of the error
async.parallel中的主要回调是什么?
主回调是对
所以实际上是这样的:
平行:
-
parallel 启动所有任务,然后等待 - 所有四个任务都安排了超时
-
超时100次触发,添加其结果(结果为
[ ,"Two"] ) -
超时200次触发,添加其结果(结果为
["One","Two"] ) -
超时400触发,返回错误和
undefined 结果(结果现在为["One","Two", undefined] ) -
parallel 注意到错误,立即返回到目前为止收到的结果 - 600超时触发,但没人在乎返回结果
系列:
-
series 触发第一个任务;它计划超时。 -
series 等到回调在200ms后被调用,然后添加结果。 (结果为["One"] ) -
series 触发第二个任务;它计划超时。 -
series 等到100ms之后调用回调,然后将结果相加。 (结果为["One","Two"] ) -
series 触发第三个任务;它计划超时。 -
series 等到回调在400毫秒后被调用,然后添加结果并由于错误而退出。 (结果为["One","Two", undefined] ) - 第四个任务永远不会执行,并且它的超时也不会被调度。
获得相同结果的事实是由于您在任务中依赖
关于如何有效地使用
如您在文档中所见:
- 对于async.series:
Run an array of functions in series, each one running once the previous function has completed.
这意味着异步将在调用" n + 1"之前等待" n"函数结束。
- 对于async.parallel
Run an array of functions in parallel, without waiting until the previous function has completed.
但是您的代码太简单了,看不到区别。
如果它们都对您有用,则应选择async.parallel,这样速度更快。