有很多方法可以处理一次运行的10个请求。
异步库 -将异步库与
.parallelLimit()
方法一起使用,您可以在其中指定要一次运行的请求数。Bluebird Promise库 -使用 Bluebird Promise 库和该
request
库将您的http.get()
东西包装成可以返回 Promise的 东西,然后将Promise.map()
并发选项设置为10
。手动编码 - 手动编码 您的请求以启动10个请求,然后每次完成一个请求,再启动另一个请求。
在所有情况下,您都必须手动编写一些重试代码,并且与所有重试代码一样,您将必须非常仔细地确定重试错误的类型,重试错误的时间,重试尝试之间的间隔以及何时重试。最终放弃(您未指定的所有内容)。
我首选的方法是使用Bluebird和promises。依次包括重试和结果收集,可能看起来像这样:
const request = require('request');const Promise = require('bluebird');const get = Promise.promisify(request.get);let remoteUrls = [...]; // large array of URLsconst 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});


