我的代码:
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);
由于异步获取请求,结果被打印为空白。如何进行这项工作,以便在结果中显示所有地址?
也许诺言可以在这种情况下提供帮助。这是我的解决方案:
'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);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句