【问题标题】:Async each series and parallel execution异步每个系列和并行执行
【发布时间】:2018-05-11 03:37:29
【问题描述】:

我有任何数组: 例子 数组 = [1 到 1 百万] 目前,我正在做:

async.eachSeries(array,function(item,callback){
some async (
callback
)
});

我想做: 5 并行执行,是否可以使用异步?

【问题讨论】:

    标签: node.js async.js


    【解决方案1】:

    异步库有很多不同的选项,可以并行运行固定数量的请求。但是,请注意,一旦您并行运行多个操作,并不能保证并行操作的完成顺序,因为这取决于服务器及其返回它们的顺序。

    以下是您的一些选择:

    每个限制

    同时迭代数组中的每个项目,最多同时进行 5 个操作。未收集任何结果。对于eachLimit(),假设您不需要结果,或者您正在收集自己的结果作为运行这些操作的副作用。

    async.eachLimit(array, 5, function(item, callback) {
       // process each item here, call callback when done
    }, function(err) {
       // done with all of them here
    });
    

    地图限制

    有点像array.map(),它迭代数组并在结果数组中按顺序收集结果。还允许您指定要在飞行中同时进行多少次操作。请注意,单个操作可能不会完全按顺序运行(它们将按顺序请求,但可能会乱序完成),但最后可用的结果数组将按正确顺序显示所有结果。

    async.mapLimit(array, 5, function(item, callback) {
       // process each item here, call callback when done with the result value
       // for each request
    }, function(err, results) {
       // done with all of them here and array of results (in order)
    });
    

    【讨论】:

      猜你喜欢
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多