我正在编写一个 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);
}
}
);
唯一的问题是,由于在时间单位内来自同一 IP 的请求过多,站点的服务器有时(可以理解)会响应 403(禁止)状态代码...
我看到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 site 模块上:
async.eachLimit(
obj.files,
limit
function (file, complete) {
complete();
},
function (err) {
}
);
但是限制使用没有记录,我不清楚...... 如果有人有任何线索...
最佳答案
大多数时候403意味着你应该限制你的请求,因为网络服务器认为你在进行DDOS攻击。
在这种情况下,您应该async.eachLimit()
async.eachLimit(obj.files, 1000,
function (file, complete) {
complete();
},
function (err) {
});
更新
我想明白了,limit
选项是并发请求的数量。
你应该减少这个数字(我的意见是 2 或 3 只是为了测试)
关于Node.js:如何限制请求列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32785484/