每次回应后,检查它是否是最后一个。
var locations = {"testurl1", "testurl2"}, results = [];
locations.forEach(function(location,index){
request.get(location,function (error, response, body){
if (!error && response.statusCode == 200) {
var jsonResponse = JSON.parse(body);
results.add(jsonResponse.address);
console.log('Address received: ' + jsonResponse.address);
if (results.length == locations.length) {
console.log('All addresses received');
console.log(results);
}
}
}
})
您也可能希望有一些超时,以便您可以显示响应,如果它需要太长时间。此外,请求可能会失败,在这种情况下,它不会被添加到结果中,因此您可以保留一个单独的计数器来检查结果。有点粗糙,但是像这样:
var locations = {"testurl1", "testurl2"}, results = [];
var failedCount = 0;
locations.forEach(function(location,index){
request.get(location,function (error, response, body){
if (!error && response.statusCode == 200) {
var jsonResponse = JSON.parse(body);
results.add(jsonResponse.address);
console.log('Address received: ' + jsonResponse.address);
} else {
// Keep a counter if a request fails.
failedCount++;
}
// Success + failed == total
if (results.length + failedCount == locations.length) {
console.log('Addresses received. ' + failedCount + ' requests have failed');
console.log(results);
}
});
});
// Set a timer to check if everything is fetched in X seconds.
setTimeout(function(){
if (results.length + failedCount < locations.length) {
console.log('10 seconds have passed and responses are still not complete.');
}
}, 10000);