每次迴應後,檢查它是否是最後一個。
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);