An easy way to handle the multiple asynchronous calls would be to use promises, and there is no need to run them synchronously and wait for one to finish. Either you can use the native promises available in Node, or you can use a promise library such as bluebird that can promisify other libraries that perform asynchronous operations.
The most simple use case would look like
var Promise = require("bluebird");
var geocoder = Promise.promisifyAll(require('geocoder'))
geocoder.geocodeAsync("Atlanta, GA")
.then(function(data){
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
console.log("Coordinates for Atlanta, GA: " + lat + "," + lng);
});
where you use the promisified function geocodeAsync
(original function name + Async
) that returns a promise with the returned data as the resolved value.
In your case where you want to perform multiple asyncronous code, you could easily create an array of promises and then let them run in parallell and handle the result when all of the promises are resolved.
var citiesToGeocode = ["Miami, FL", "New York", "Orlando, FL", "Rio de Janeiro, Brazil"];
var geocodePromises = [];
for (var i = 0; i < citiesToGeocode.length-1; ++i) {
geocodePromises.push(geocoder.geocodeAsync(citiesToGeocode[i]));
}
Promise.all(geocodePromises).then(function(result) {
result.forEach(function(geocodeResponse){
console.log("Coordinates for " + geocodeResponse.results[0].formatted_address +": " + geocodeResponse.results[0].geometry.location.lat + "," + geocodeResponse.results[0].geometry.location.lng);
});
});
Using the same approach you can use reverseGeocodeAsync
to lookup information from coordinates.