1

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 .

  • See this answer: http://stackoverflow.com/questions/38426745/how-do-i-return-the-accumulated-results-of-multiple-parallel-asynchronous-func/38427271#38427271 – slebetman Jul 26 '16 at 06:11
  • Your choices are to use promises and `Promise.all()`, use the Async library or write a simple counter and just count when all the async tasks are done and then call your function. You won't be turning async code into synchronous code - that doesn't happen in Javascript. You will be keeping track of when all the async operations are done, collecting the results and then calling some callback with the final results/error. There are hundreds of other related questions here on SO. – jfriend00 Jul 26 '16 at 07:00

2 Answers2

1

You're looking for Promise.all.

Nick Cox
  • 6,164
  • 2
  • 24
  • 30
1

You can use async library to achieve what you need. This library have a broad range of features for syncrhonious tasks. For example async.waterfall or async.series can do the job here. You can use them in your callback function to have a synchronious behaviour.

Mika Andrianarijaona
  • 1,619
  • 17
  • 29