How to use async.each in node.js?
The signature of the is like:-
async.each(<takes array here>,function(eachItemOfArray,callback){
},function(error,result){
if(error)
{
console.log(error);
}
else
{
console.log(result);
}
})
example:-
async.each([1,2,3,4],function(eachItemOfArray,callback){
//execute any async function or service here.
})
- While iterating each objects of the array and calling any other service in between if any error occurs execution call just reach to the third parameter of each function that is a function having error and result (function(error,result){}) and execute if(error){} statement.
- If any error occurs it does not look for any other objects of the array.
Here is the working example:-
here is have used getLatLng to get latitude and longitude of the location using "node-geocoder" node module.
let async = require('async');
var NodeGeocoder = require('node-geocoder');
var options = {
provider: 'google',
httpAdapter: 'https',
apiKey: '<you api key>', // for Mapquest, OpenCage, Google Premier
formatter: null
};
var geocoder = NodeGeocoder(options);
exports.getRecordsWithLatLng = function (array, cb) {
var finalResult = [];
async.each(array, (data, callback) => {
getLatLng(`${data.street?data.street+" ,":''} ${data.city}, ${data.name}, ${data.zipcode}, Brazil`, (err, latlng) => {
console.log(data, latlng);
if (err) {
callback(err);
return;
}
if (latlng && latlng.length > 0 && latlng[0].latitude && latlng[0].longitude) {
data.latitude = latlng[0].latitude;
data.longitude = latlng[0].longitude;
finalResult.push(data);
callback();
} else {
finalResult.push(data);
callback();
}
});
}, (err, result) => {
if (err) {
console.log(err);
cb(array);
} else {
cb(finalResult);
}
})
}
var getLatLng = exports.getLatLng = function (address, callback) {
geocoder.geocode(address, function (err, res) {
if (err)
callback(err, null)
else
callback(null, res)
});
}
No comments:
Post a Comment