0

I am trying to get distances between two addresses using Nodejs and the distancematrix API from google maps. I realize that I need to wait for the API to complete 'getting' the distance before I can actually use it, but I am having trouble figuring out how to do this. I have already looked at other examples online but can't seem to get the correct return value.

const origins = [{lat:33.1581549623887,lng: -96.58113451598159}]
const destinations = ["9200 World Cup Way, Frisco, TX 75033"]

function getDistances(origins, destinations){
    client.distancematrix({
        params:{
            origins:origins,
            destinations:destinations,
            key:"some-key",
            units:"imperial"
        }
    })
    .then((r) => {
        if(r.data.rows[0].elements != undefined){
            // console.log(r.data.rows[0].elements)
            return(r.data.rows[0].elements);
        }
      }) 
    .catch((e) =>{
        console.log(e.response.data.error_message);
    })
}
    
async function getClosestField(employee, games){
  closestField = games[0]
  let distance = await getDistances(origins,destinations)
  console.log(distance) //ALWAYS UNDEFINED

      return(distance)
}

getClosestField(employees[0],games)

Note: I have the appropriate key and it's not actually "some-key"

The result of console.log(distance) is undefined.. How can I properly wait for getDistances() to complete before I console log it?

Since the client returns a promise, I thought the .then portion would only execute after completion.

wawaloo_17
  • 157
  • 3
  • 10
  • Yes, it does, but `console.log(distance)` is not in that `.then` portion. You can (should) however `return` the promise chain from `getDistances`, and use `getDistances(origins, destinations).then(distance => { … })` – Bergi Nov 24 '20 at 22:03
  • Your updated `async function getClosestField` looks good. Now you're just missing the `return` statement in the first line of the `getDistances` function. (You might want to rewrite that into an `async function getDistances(origins, destinations){ try { const r = await client.distancematrix({…}); … } … }` as well, though) – Bergi Nov 24 '20 at 22:21

0 Answers0