How do I put Axios.get back into a variable?

Asked

Viewed 1,228 times

1

I made an access to the database and with Axios.get I got the return but I need to store this return in a variable so I can use it further, but when I tried to get it as a result: Promise { : "pending" }, follow the code of what I am trying to do below:

async function obterLocalizacao() {
    await axios.get('http://localhost:3333/informacoes')
        .then(response => { return response })
        .catch(error => console.log(error))
}

console.log(obterLocalizacao());

The question is, how to store the value of Response in another variable to use in the future?

1 answer

0

all right? When a requisition is made, this is nothing more than a Promise, as Voce is returning the value of an asynchronous function is always a precedent, so its function also returns a precedent, so what you should do is something very similar to this.

 function getLocais() {
        return fetch('https://servicodados.ibge.gov.br/api/v1/localidades/regioes');
    }

and then to use the return of this function, it’s something like this

const r = await getLocais();

And you can use the value of this variable. To treat the return you can do something more cool like this:

async function getLocais() {
  try {
    const r = await fetch('https://servicodados.ibge.gov.br/api/v1/localidades/regioes');
    return r;
  } catch (e) {
    return null
  }
}

And you can make more changes than something trivial like just a request.

Remember, an async function always returns a Promise, so you should either use the then and the catch to get its value, using the await along with the try/catch if you want to treat the result

Browser other questions tagged

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