您需要注意的是:
目标站点是否有速率限制,如果您尝试请求太多太快可能会被阻止访问?
目标站点可以同时处理多少个请求而不降低其性能?
您的服务器有多少带宽?
您自己的服务器可以同时处理和处理多少个请求,而不会导致过多的内存使用或固定 CPU。
一般来说,管理所有这些的方案是创建一种方法来调整您启动的请求数量。有许多不同的方法可以通过同时请求的数量、每秒的请求数、使用的数据量等来控制这一点......
最简单的开始方法是控制您同时发出的请求数。可以这样做:
function runRequests(arrayOfData, maxInFlight, fn) {
return new Promise((resolve, reject) => {
let index = 0;
let inFlight = 0;
function next() {
while (inFlight < maxInFlight && index < arrayOfData.length) {
++inFlight;
fn(arrayOfData[index++]).then(result => {
--inFlight;
next();
}).catch(err => {
--inFlight;
console.log(err);
// purposely eat the error and let the rest of the processing continue
// if you want to stop further processing, you can call reject() here
next();
});
}
if (inFlight === 0) {
// all done
resolve();
}
}
next();
});
}
然后,你会像这样使用它:
const rp = require('request-promise');
// run the whole urlList, no more than 10 at a time
runRequests(urlList, 10, function(url) {
return rp(url).then(function(data) {
// process fetched data here for one url
}).catch(function(err) {
console.log(url, err);
});
}).then(function() {
// all requests done here
});
可以通过向其添加时间元素(每秒不超过 N 个请求)甚至带宽元素来使其变得任意复杂。
我想在一个请求完成后调用一个请求。
这是一种非常缓慢的做事方式。如果你真的想要,那么你可以将1 的maxInFlight 参数传递给上述函数,但通常情况下,通过允许5 到50 个同时请求,事情会运行得更快并且不会引起问题。只有测试才能告诉您特定目标站点和特定服务器基础架构的最佳位置以及您需要对结果进行的处理量。