【问题标题】:async.eachLimit executes only for the limit specified and not the whole arrayasync.eachLimit 仅针对指定的限制而不是整个数组执行
【发布时间】:2018-11-21 06:35:17
【问题描述】:

我正在使用 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

【问题讨论】:

  • 对不起 console.log 语句:它应该是 console.log("in with item id: ",itemId)
  • @Rashika 你能把 npm 库包的链接贴在这里吗?
  • 第二个参数有限制,把它增加到你认为包含所有的。这里async.eachLimit(listOfItemIds, 10 , function(itemId).
  • 或者,如果您想达到某种限制,您可以对列表项的长度进行数学计算。如listOfItemIds.length - 10 或得到大约一半的Math.floor(listOfItemIds.length / 2)。然后将其用作第二个参数。

标签: node.js npm async.js


【解决方案1】:

您还需要传递一个 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

希望这会有所帮助!

【讨论】:

  • 非常感谢!这是完美的解决方案!
  • 顺便标记一下我的答案,对以后的参考很有用。
  • 您可以使用异步函数,这样当它们完成时,异步继续。 async.eachLimit(listOfItemIds, 10, async function(itemId) { console.log("in with item Id: ",itemId); }, function(err) { if(err) { console.log("err : ",err); throw err; } });
  • 出于某种原因,即使使用异步,我也需要提供回调!
猜你喜欢
  • 2021-01-19
  • 2018-10-04
  • 2015-01-19
  • 1970-01-01
  • 2022-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
相关资源
最近更新 更多