Well, let me introduce you to async
's concat
function. Here is your modified program.
var request = require('request');
var async = require('async');
var addresses = [
"Tokyo",
"Moscow",
"Bagdhad",
"Mountain View",
"New York",
];
function accessUrl( address, callback ) {
options ={
headers: {'user-agent': 'Mozilla/5.0'},
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + address,
json: true
};
request.get(options, function(err, response, body_json) {
if( !err && response.statusCode === 200 ){
return callback(null, [[ address, body_json['weather'][0]['main'],
Math.round(body_json['main']['temp']-273.15)]]);
}
else{
return callback(err);
}
});
}
async.concat (addresses, accessUrl, function(err, result) {
if (err) {
console.error(err);
} else {
console.log(result);
}
});
Output
[ [ 'Mountain View', 'Haze', 17 ],
[ 'Bagdhad', 'Clear', 18 ],
[ 'New York', 'Clear', 26 ],
[ 'Tokyo', 'Clouds', 22 ],
[ 'Moscow', 'Clouds', 3 ] ]
You don't have to synchronize the results yourself. concat
does that for you.
If you are interested to know how async's concat works, try this