使用asynchronous和请求模块限制请求

我将asynchronous和请求模块组合在一起,以asynchronous方式和速率限制来发出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. }); 

数据包含我要求的所有url。 我使用forEachLimit方法将并发请求的数量限制为5。 这段代码会使第5个请求停止。

在asynchronous文档中,它说:“迭代器传递一个callback函数,一旦完成,就必须调用它”。 但是我不明白,我该怎么做来表示请求已经完成?

首先,您应该将callback添加到您的迭代器函数中:

 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调用它的callback函数:

 async.forEachLimit(data, 5, requestApi, function(err){ // err contains the first error or null if (err) throw err; console.log('All requests processed!'); }); 

asynchronous在接收到第一个错误或所有请求成功完成后立即调用其callback。