Node.js: 如何限制请求列表?

Node.js: How to throttle a list of requests?

我正在编写一个 node.js 应用程序,它需要从提供商的页面列表中获取一些数据:

var list = [
  { url: 'http://www.example.com/1' },
  { url: 'http://www.example.com/2' },
  ...
  { url: 'http://www.example.com/N' },
];

目前我正在使用 async.each,效果很好:

async.each(
  list, // 1st param is the array of items
  function(elem, callback) { // 2nd param is the function that each item is passed to
    request(elem.url, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log(body);
      }
    }),
  },
  function(err) { // 3rd param is the function to call when everything's done
    if (err) {
      console.error('Error in the final async callback:', err);
    }
  }
);

唯一的问题是网站的服务器有时(可以理解)响应 403 (forbidden) 状态代码,由于同一时间段内同一 IP 的请求过多...

我看到async也提供了一个whilst()方法,其例子是:

var count = 0;
async.whilst(
  function () { return count < 5; },
  function (callback) {
    count++;
    setTimeout(callback, 1000);
  },
  function (err) {
    // 5 seconds have passed
  }
);

但我不知道如何将它与列表一起使用,或者如何将它与 async.each 结合使用...:-(

所以答案是:如何限制(限制)node.js 中的异步请求列表?

P.S.: 更清楚地说,我不想(如果可能的话)排队 请求,因为请求可能需要很长时间才能完成...:我只希望请求 启动 在定义的时间间隔内(比如每个请求之间 5 ~ 10 秒...) .


更新:

在 alireza david 发表评论后,我确实尝试使用 async.eachLimit,这对我来说看起来很有前途......这是它在模块 github [=19= 上的用法示例]:

async.eachLimit(
    obj.files,
    limit
    function (file, complete) {
      complete();
    },
    function (err) {
    }
);

但是没有记录限制用法,我也不清楚... 如果有人有任何线索...

大多数时候 403 意味着您应该限制您的请求,因为 Web 服务器认为您在进行 DDOS 攻击。

在这种情况下你应该async.eachLimit()

async.eachLimit(obj.files, 1000,
    function (file, complete) {
      complete();
    },
    function (err) {

    });

更新 我想明白了,limit 选项是并发请求数。 你应该减少这个数字(我的意见是 2 或 3 只是为了测试)