2015-07-12 81 views
0

我的代碼:製作GET請求,裏面for循環

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(results); 

結果打印爲空白由於異步GET請求。我如何使這項工作,所以我在結果中的所有地址?

回答

1

也許諾言可以幫助在這種情況下。這是我的解決方案:

'use strict'; 

var request = require('request'); 
var Q = require('q'); 
var defer = Q.defer(); 
var promise = defer.promise; 
var locations = [ 
    'http://www.google.com', 'http://www.instagram.com' 
], 
results = []; 

locations.forEach(function(location, index) { 
    request.get(location, function(error, response, body) { 
    if (!error && parseInt(response.statusCode) === 200) { 
     results.push(response.statusCode); 
    } 
    if ((locations.length - 1) === index) { 
     defer.resolve(); 
    } 
    }); 
}); 

promise.then(function() { 
    console.log('RESULTS:', results); 
}); 

我測試了這個,它工作正常。承諾簡要解釋here

2

每次迴應後,檢查它是否是最後一個。

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);