Empty Array In Callback
I am using geocoder npm module to convert the address to lat,long. This API reads address from file google.csv using fast csv npm module after that result i.e addresses are passed
Solution 1:
You'll want to use async.parallel. Since you are calling multiple geocoder.geocode. Since it is asynchronous, your function returns a value before they have ended.
functiongetLatLong(responseObj, callback){
var responseArray = responseObj.adrressarray;
var geocodeArray = responseArray.Success.slice(1);
var geoLatLongFunctions = geocodeArray.map(function(x) {
returnfunction(cb){
var addressOfRow = x.toString();
geocoder.geocode(addressOfRow, function (err, data) {
if(err){
cb(err);
}
var latitude = data.results[0].geometry.location.lat;
var longitude = data.results[0].geometry.location.lng;
var address = data.results[0].formatted_address;
var obj = [{"latitude":latitude,"longitude":longitude, "address":address}];
cb(null,obj);
});
};
});
async.parallel(geoLatLongFunctions,callback);
}
Here, what I've done is make your geocodeArray.map return a function instead. And used async.parallel to execute them. Once all of them has finished, the callback will be called containing the results of all executions.
Solution 2:
You are calling the callback too soon (synchronously), while the array is only populated later (asynchronously).
Make these changes:
functiongetLatLong(responseObj, callback){
var latlongArray = []; // Define & initialise array here!var responseArray = responseObj.adrressarray;
var geocodeArray = responseArray.Success.slice(1);
geocodeArray.map(function(x) {
var addressOfRow = x.toString();
geocoder.geocode(addressOfRow, function (err, data) {
if(err){
returncallback(err);
}
var latitude = data.results[0].geometry.location.lat;
var longitude = data.results[0].geometry.location.lng;
var address = data.results[0].formatted_address;
var obj = [{"latitude":latitude,"longitude":longitude, "address":address}];
latlongArray.push(obj);
// Only call callback when array is completeif (latlongArray.length == geocodeArray.length) {
callback(null, latlongArray);
}
})
});
}
Post a Comment for "Empty Array In Callback"