Difficulty with Asymchronism - Javascript/Reactjs/Google Maps/Distance Matrix API

Asked

Viewed 49 times

-2

Good afternoon, everyone,

I’m new in the area and I’m having difficulty developing a code that runs Function2 only after the return of Function1.

How can I adjust the code for Function2 to run only after the return of Function1?

functionExample = () => {
    var distance = require('google-distance-matrix')
    var origins = [location1]
    var destinations = [location2]

// Função1:

    distance.matrix(origins, destinations, (err, distances) => {
      if (err) {
        console.error(err, 'status', distances1.status)
        console.log("Erro")}

      if (distances.status === "OK") {
        ArrayExample.push((distances.rows[0].elements[0].distance.value / 1000))}
    })

// Função2:

functionExample2()

}

1 answer

0


Hello, welcome to the world of Javascript what you want to achieve are asynchronous functions, I recommend reading the documentation of Promisses to better understand what is happening but a solution to your problem is simple, the return of "Distance.Matrix" is a promisse, from this can abstract to a variable using async / await, would look something like :

const response = await distance.matrix(origins, destinations)

Remember to make your function asynchronous to avoid undefined values for this do :

async functionExample() { ... <bloco da sua função>

Following this strategy by calling functionExample() it will return a promisse and you can treat them with then & catch

The call to your asynchronous function

functionExample().then((resultado) => {
// aqui vai poder utilizar seu resultado
}).catch((erro) => {
// aqui vai cair quando tiver um erro em sua função   
})

I hope you understand and can use asynchronous functions without any more problems now.

Browser other questions tagged

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