I'm writing a backend API in Node.js, however the coolest feature of it, async functions are now challenging me with a new problem.
I have a list of objects called Person with the information of ID, Latitude, Longitude. And what I simply want to do is sort them according to their distance to a certain point (Let's say Point A).
When I would like to loop through each object, make a request, (I'm using module request. Can be checked in here). However due to it's nature Node first loops through all the objects, sends requests, and doesn't wait for the reply. So when the reply comes I cannot understand which reply is for which person. Even though it list's their ID in correct order when I check through Redis I see that responses of the Google API request's are not ordered. Here is my code for a better understanding;
for(var i = 0;i < result.length;i++){
console.log("the iteration time: "+i);
tempObject = JSON.parse(result[i]);
console.log("\n I make the request for key: "+tempObject.ID);
request('http://maps.googleapis.com/maps/api/directions/json?origin='+tempObject.lat+
','+tempObject.lon+'&destination=' + targetLatitude + ',' + targetLongitude
+ '&sensor=false',
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Lat: "+tempObject.lat);
console.log("Lon: "+tempObject.lon);
console.log("key: "+list[counter]);
tempObj = JSON.parse(body);
counter++; //For loop end check
console.log("i: "+i);
duration = tempObj.routes[0].legs[0].duration.value;
console.log("Duration: "+tempObj.routes[0].legs[0].duration.value+"\n");
if(counter == result.length){
//end loop
}
}
});
}
I would like to state I do not have any trouble with my code. I just cannot find the solution for this problem: How can I get the id's of my Person list, when responses from Google Maps Direction API does not come ordered. Loop makes the requests one by one for each Person object in list, however the responses from Google are not in order thus I cannot obtain their ID's.
I even thought like putting the objects in a list, and later by checking the starting point lat and long in the API response, comparing them with the Person in the list, I can identify whose response came first, but that did not work out as well. Any suggestions?
PS: If you see word "key" it means id of the user. I'm using Redis so I tend to use "key" as well.