假设您有一个包含3~5个网址的列表。请求应每5秒钟一个一个地进行。我编写的代码如下:
setInterval(() => {
array.foreach(element => {
request
.get(element.url)
.on('response', function(response) {
console.log(response);
}
});
}, 5000)
但是因为排队的setInterval比执行请求更快,所以.on
回调没有响应。我想,在排队setInterval之前,我必须确保我已完成.on
回调。
我该怎么做?
答案 0 :(得分:0)
你能试试吗?
var requestArray = [
{
url: 'some URL number 1'
},
{
url: 'some URL number 2'
},
{
url: 'some URL number 2'
}
]
function makeRequests(){
for(var i=0; i<requestArray.length; i++){
request.get(requestArray[i].url)
.on('response',function(response){
console.log(response);
if(i == requestArray.length - 1)//You can check any condition here if you want to stop executing get requests{
makeRequests();
}
})
}
}
答案 1 :(得分:0)
推荐Async.js模块。
如果要解析异步循环,可以:
var i = 0;
async.whilst(
function() { return i < array.length; },
function(next) {
var elemet = array[i++];
request
.get(element.url)
.on('response', function(response) {
console.log(response);
// Do next while 5s passed
setTimeout(next, 5000);
}
}
},
function (err, n) {
// All Task over
}
);
或者如果你想尝试一些并发:
// create a queue object with concurrency 2
var q = async.queue(function(task, next) {
console.log('request ' + task.url);
request
.get(task.url)
.on('response', function(response) {
console.log(response);
next();
}
}
}, 2);
// assign a callback
q.drain = function() {
console.log('all task have been processed');
};
// Push a request task to the queue every 5s
setInterval(function () {
let task = array.shift()
if (task) {
q.push(task, function(err) {
console.log('finished processing', task.url);
});
}
}, 5000);