Google Distance Matrix, wait callback to continue loop

Asked

Viewed 49 times

0

I’ve done a lot of research on the subject and I still can’t find a solution.

When I run the code below, the loop proceeds before the API callback.

In the callback the variable this.userRoute.newRoute[i]. address is changed, so I need the loop to wait for callback, to proceed from the new value that was inserted into the array, which before callback does not exist and returns "Undefined".

My question is whether I can get the loop to wait for the callback to run to continue the execution.

for(let i = 0; i < this.userRoute.route.length; i++){      
  service.getDistanceMatrix(
    {
      origins: [this.userRoute.newRoute[i].address],
      destinations: composeDestination,
      travelMode: 'DRIVING',
    }, this.calcRouteDistanceResult.bind(this)
  );
}

1 answer

0

I actually found that I don’t need to do it inside a loop.

The API itself allows you to provide multiple sources, and returns the distance from each source to each of the destinations, so just handle the json.

Ex. Origin A => Destination A => 2km Destination B => 4km Origin B => Destination A => 2km Destination B => 4km

Browser other questions tagged

You are not signed in. Login or sign up in order to post.