2015-07-12 82 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);