0

I send request to routing service that returns route summary as json (waypoints, distance, time, etc). I do it in loop because I need to calculate multiple roots and get their distances to array. I understand that JS works asynchronously and if I send e.g. two requests, I can get result from second request faster than from first. But is there any way to make it work like "req1 sent, got result from req1, req2 sent, result from req2 etc"? I read about setting asynch parameter false but 1-st: it didn't work, 2-nd: it's not a good practise, as I see. Here's my code:

coords -- array with coordinates like [[lat0, lng0], [lat1, lng1]...]
distances -- array where I want to put distances between points

//function to get summary of one route 
function getRoutSummary(i, j) {
                var url = 'https://api.mapbox.com/directions/v5/mapbox/driving/' +
                        coords[i][1] + ',' + coords[i][0] + ';' +
                        coords[j][1] + ',' + coords[j][0] +
                        '?geometries=geojson&access_token=my api key';

                var req = new XMLHttpRequest();

                req.responseType = 'json';

                req.open('GET', url, true);

                req.onload = function () {
                    var jsonResponse = req.response;
                    var distance = jsonResponse.routes[0].distance;
                    console.log('Distance between ' +
                        'coords[' + i  +'][1]' + ',' + 'coords[' + i + '][0]' + ' and ' +
                        'coords[' + j  +'][1]' + ',' + 'coords[' + j + '][0]' +
                        ' is ' + distance);
                    distances.push(distance);
                };
                req.send();
        }

//function to get all distances. Console.log just to make me comfortable
function getAllRoutes(){
            console.log('Begin getAllRoutes');
            for (var i = 0; i < coords.length; i++){
                for (var j = 0; j < coords.length; j++){
                    getRoutSummary(i, j);
                }
            }
            console.log(distances);
        }

So now if I have three points p1, p2, p3 I want to get array with distances between them in that order: [p1p1, p1p2, p1p3, p2p1, p2p2...], but this code gives me different order all the time like [p1p3, p2p1, p3p2..] or [p3p3, p2p1..]. I considered using callback but didn't figure out how to use it here honestly. Any suggestions?

indeedme
  • 25
  • 8
  • If the order is your only problem then you're lucky -> [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas May 25 '19 at 16:44
  • @Andreas - don't agree that's a dup. It uses jQuery and there is no iteration through async calls. – Randy Casburn May 25 '19 at 16:54
  • @RandyCasburn Where did you find a dupe-vote from me? o.O And while the linked question uses jQuery the answer is valid for any asynchronous function (`$.ajax()`, `XMLHttpRequest.onreadystatechange`, event handlers, ...) – Andreas May 25 '19 at 16:56
  • Yeah, probably meant IMO don't think it's similar. – Randy Casburn May 25 '19 at 17:12

0 Answers0