This question is different than the questions that are posted before on Asynchronous processes . I am working an a uber like application and i am using firebase as backend . I made a server to handle some tasks like assignment of orders to drivers . When an order appears i need to find distance between all the drivers and customer using google maps api . Below is function given which i am using to calculate distance between drivers and customer.
function calculatingDistance(fromLat,fromLong,toLat,toLong){
var distanceDurationObject={};
var options = {
host: 'maps.googleapis.com',
path: '/maps/api/directions/json?origin='+fromLat+','+fromLong+'&destination='+toLat+','+toLong+'&key=AIzaSyBsoc1PZOItqHNYc5z2hW_ejPFi2piRR8Y',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
var req = https.get(options, function(res) {
//buffering alll data
var bodyChunks = [];
res.on('data', function(chunk) {
// You can process streamed parts here...
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
json = JSON.parse(body);
//parsing json returned
var routes =json["routes"];
var legsObject=routes[0].legs;
var legsFirstArray=legsObject[0];
//Our Required Distance between two points
var distanceValue=legsFirstArray.distance.value;
var durationValue=legsFirstArray.duration.value;
console.log(distanceValue+" "+durationValue);
distanceDurationObject.distance=distanceValue;
distanceDurationObject.duration=durationValue;
});
});
req.on('error', function(e) {
console.log('ERROR: ' + e.message);
//try to add this error to a file
});
}
Flow of finding distances between customer and taxi drivers given bellow.
1)Once order appears in database it is fetched into the server and saved in a map containing key as id of customer and value as object in which customer's latitude and longitude are provided.
2)There is also a map containing key as id of drivers and value as object containing latitude and longitude of drivers.
3)Customers distance with all the drivers is computed using the function given above and the one driver with the least distance receives a notification.
Problem :
What i want is that once the order appears, in a for loop i add "calculatingDistance(fromLat,fromLong,toLat,toLong)" functions in a queue with toLat and toLong having latitude and longitude of drivers and fromLat and fromLong having latitude and longitude of customers . After the for loop i execute all the callbacks and once all those callbacks are completed a function x() is called and distance durationObject from all those callbacks is returned to function x();
TL;DR Basically i just want data from all asynchronous functions into one function after their complete execution .