首页 > 解决方案 > async.eachLimit 仅针对指定的限制而不是整个数组执行

问题描述

我正在使用 npm 异步库(https://caolan.github.io/async/docs.html)来限制并行请求的数量。下面是我的代码:

    async.eachLimit(listOfItemIds, 10, function(itemId)
    {
      console.log("in with item Id: ",itemId);
    }, function(err) {
         if(err) 
         {
           console.log("err : ",err);
           throw err;
         }
    });

但它不会对所有 listOfItemIds 执行,它只对前 10 个执行并退出。

下面是输出:

in with item id:  252511893899
in with item id:  142558907839
in with item id:  273235013353
in with item id:  112966379563
in with item id:  192525382704
in with item id:  253336093614
in with item id:  112313616389
in with item id:  162256230991
in with item id:  282981461384
in with item id:  263607905569

标签: node.jsnpmasync.js

解决方案


您还需要传递一个 callback() 方法。

这里看看下面的代码,这将起作用。

async.eachLimit(listOfItemIds, 2, function(itemId, callback)
{
  console.log("in with item Id: ",itemId);
  callback();
}, function(err) {
      if(err) 
      {
        console.log("err : ",err);
        throw err;
      }
});

这将打印数组中的所有元素,我将并行执行的数量限制2在上述情况下。

希望这可以帮助!


推荐阅读