Node using Axios with express, I want to wait for Promises

Asked

Viewed 141 times

1

I’m willing to expect the value of one Precedent that is inside another


const URL = 'url da api que eu quero consumir'
const AuthStr = 'meu token'

function GET (){
    axios.get(URL, { headers: { Authorization: AuthStr } })
        .then(response => {
            console.log(response.data);
            return response.data
        })
        .catch((error) => {
            console.log('error ' + error);
        });
};

app.get("/", (request, response) => {
  let data = GET();;
  
  return response.json(data);
})

the problem is that I can’t make the app.get wait for Xios to return JSON

2 answers

1


You need to make some modifications to your code

You need to warn that your function is asynchronous, you need to wait for the Axios response (which is asynchronous, and .then and .error are just ways to treat asynchronity) and wait for the GET response in your app.get

So here’s how it’s gonna be:

const URL = 'url da api que eu quero consumir'
const AuthStr = 'meu token'

async function GET (){
    const resposta = await axios.get(URL, { headers: { Authorization: AuthStr } })

    return resposta.data;
};

app.get("/", async (request, response) => {
  let data = await GET();
  
  return response.json(data);
})

When you use ASYNC, you need to warn your entire call stack that you need to wait for the asynchronous call to respond, so in case you make use of await (in the call) and async (in the function itself)

NOTE: Your Return in Sponse is not good for much there, it is returning to nowhere. The server response is basically in Response, in your case Response.json(data)

0

  • 1

    hello thank you so much was this push I needed, had previously testing using async await but was not understanding how to do I put the async directly in the express parameter and it worked like this app.get("/", async (request, Response) => { Return data = await GET(); }

Browser other questions tagged

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