I'm writing a test code which gathers the result from Web APIs on node.js by using 'request.js' and 'async.js'.
Here's my sample code;
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(address, body_json);
}
else{
console.log('error');
}
});
}
function showContent( address, body_json ) {
console.log( "%s : %s, %s (C)", address, body_json['weather'][0]['main'],
Math.round(body_json['main']['temp']-273.15));
return [ address, body_json['weather'][0]['main'],
Math.round(body_json['main']['temp']-273.15)];
}
var result = [];
async.map( addresses, function( item, callback ) {
result.push (accessUrl( item, showContent ));
}, function(err) {
});
console.log(result);
However, the result is;
~$ node asyncsample1.js
[ undefined, undefined, undefined, undefined, undefined ]
Tokyo : Clear, 23 (C)
Mountain View : Mist, 10 (C)
Bagdhad : Clear, 10 (C)
New York : Clear, 22 (C)
Moscow : Clouds, 4 (C)
console.log() in the callback function showContent() shows the proper result but the gathered results are all 'undefined'.
How can I get the results in var result[]?