[英]request api in foreach
I have an array
of data, against which I query an api
using request
. 我有一个数据
array
,我可以使用request
查询一个api
。 With a callback
executing after each response for the request that is made. 在对请求作出的每个响应之后执行
callback
。 However, in doing so, I end up launching parallel requests for all the items in the array. 但是,这样做最终导致对数组中的所有项目发起并行请求。 Here is what I am doing:
这是我在做什么:
exports.getData = function(arr, cb){
arr.forEach(function(data){
var query = {
//some data here
};
request({
url: 'http://x/y',
json: query,
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}, function(error, res, body){
if (error){
console.log(error);
} else{
cb(res.body);
}
});
});
};
I want to setTimeOut
of x seconds
in the above code. 我想在上面的代码中设置
x seconds
setTimeOut
。 Should I implement a naive delay after each request? 我应该在每次请求后实施天真的延迟吗? Or something else?
或者是其他东西?
Updated : parallel request to series of request. 已更新:将并行请求更改为一系列请求。
You should use series of request. 您应该使用一系列请求。 use
async
module. 使用
async
模块。 see below 见下文
exports.getData = function(arr, cb){
// make an array of function
var funcArray = [];
arr.forEach(function(data){
var query = {
//some data here
};
funcArray.push(function(callback){
request({
url: 'http://x/y',
json: query,
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}, function(error, res, body){
// 5 second interval for each request
setTimeout(function(){ callback(error, body); }, 5000);
});
});
});
// now run all tasks on series
async.series(funcArray,function(err, result){
// now you will get result for all request
// handle error
// do what ever you want with result
});
}
forEach loop will ideally end in no time, so you can first add all query parameters in queryPool and then execute them one by one. 理想情况下,forEach循环将立即结束,因此您可以首先在queryPool中添加所有查询参数,然后一个一个地执行它们。
You can refer to this code. 您可以参考此代码。
exports.getData = function(arr, cb){ var queryPool = []; function execQuery(){ if(queryPool.length == 0) return var query = queryPool.slice(0,1) queryPool = queryPool.slice(1,queryPool.length) request({ url: 'http://x/y', json: query, method: 'POST', headers: { 'Content-Type': 'application/json' } }, function(error, res, body){ if (error){ console.log(error); } else{ cb(res.body); } execQuery(); }); } arr.forEach(function(data){ var query = { //some data here }; queryPool.push(query); }); execQuery(); };
This code assumes function given in request executes in all conditions, failure or success. 该代码假定请求中给定的功能在所有条件下(失败或成功)均执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.