运行 1000 个请求,以便一次仅运行 10 个

Soo*_*ead 3 javascript asynchronous node.js promise

使用node.js,我希望http.get以一次仅运行 10 个(或 n 个)的方式访问多个远程 url。

如果本地发生异常(m 次),我还想重试请求,但当状态代码返回错误(5XX、4XX 等)时,请求将被视为有效。

这对我来说真的很难理解。

问题:

  1. 无法尝试捕获 http.get,因为它是异步的。
  2. 需要一种在失败时重试请求的方法。
  3. 我需要某种信号量来跟踪当前活动的请求计数。
  4. 当所有请求完成后,我想获取列表中所有请求网址和响应状态代码的列表,我想对其进行排序/分组/操作,因此我需要等待所有请求完成。

似乎对于每个异步问题都建议使用 Promise,但我最终嵌套了太多 Promise,它很快就变得无法编码。

jfr*_*d00 5

有很多方法可以处理同时运行的 10 个请求。

  1. 异步库- 使用异步库的方法.parallelLimit() 可以指定一次要运行的请求数。

  2. Bluebird Promise Library - 使用Bluebird Promise 库并将request您的库包装http.get()到可以返回 Promise 的内容中,然后Promise.map()与设置为 的并发选项一起使用10

  3. 手动编码- 手动编码您的请求以启动 10 个请求,然后每次完成一个请求时启动另一个请求。

在所有情况下,您都必须手动编写一些重试代码,并且与所有重试代码一样,您必须非常仔细地决定重试哪些类型的错误、重试的时间、重试尝试之间的退避程度以及何时重试。最终放弃(所有你没有指定的事情)。

其他相关回答:

如何从nodejs应用程序发出数百万个并行http请求?

百万个请求,一次 10 个 - 手动编码示例


我首选的方法是使用 Bluebird 和 Promise。包括按顺序重试和结果收集,可能如下所示:

const request = require('request');
const Promise = require('bluebird');
const get = Promise.promisify(request.get);

let remoteUrls = [...];    // large array of URLs

const maxRetryCnt = 3;
const retryDelay = 500;

Promise.map(remoteUrls, function(url) {
    let retryCnt = 0;
    function run() {
        return get(url).then(function(result) {
            // do whatever you want with the result here
            return result;
        }).catch(function(err) {
            // decide what your retry strategy is here
            // catch all errors here so other URLs continue to execute
            if (err is of retry type && retryCnt < maxRetryCnt) {
                ++retryCnt;
                // try again after a short delay
                // chain onto previous promise so Promise.map() is still
                // respecting our concurrency value
                return Promise.delay(retryDelay).then(run);
            }
            // make value be null if no retries succeeded
            return null;
        });
    }
    return run();
}, {concurrency: 10}).then(function(allResults) {
     // everything done here and allResults contains results with null for err URLs
});
Run Code Online (Sandbox Code Playgroud)