我正在组合async和request模块,以异步方式和速率限制发出api请求。
这是我的代码
var requestApi = function(data){
request(data.url, function (error, response, body) {
console.log(body);
});
};
async.forEachLimit(data, 5, requestApi, function(err){
// do some error handling.
});
数据包含我发出请求的所有网址。使用forEachLimit方法将并发请求数限制为5。此代码使前5个请求停止。
在异步文档中,它说“迭代器传递一个必须在完成后调用的回调”。但我不明白这一点,我该怎么做才能表明请求已经完成?
答案 0 :(得分:5)
首先,您应该为迭代器函数添加回调:
var requestApi = function(data, next){
request(data.url, function (error, response, body) {
console.log(body);
next(error);
});
};
next();
或next(null);
告诉Async所有处理都已完成。 next(error);
表示错误(如果error
不是null
)。
处理完所有请求后Async使用err == null
调用其回调函数:
async.forEachLimit(data, 5, requestApi, function(err){
// err contains the first error or null
if (err) throw err;
console.log('All requests processed!');
});
Async在收到第一个错误后或在所有请求成功完成后立即调用其回调 。