[Vuejs]-Wait for response in a request in axios

2👍

You need to wait for the first request to resolve Aka finished and then you can make the second request using async/await logic.

Here’s the code-

async function req(){
let access_token = '';
var config = {
    method: 'post',
    url: <url1>,
    data: <data>
    headers: {
      header1: <header>
      }
}

const {data} = await axios(config);

access_token = data.access_token

config = {
    method: 'post',
    url: <url2>,
    headers: {
      Authorization: `Bearer ${access_token}`
      }
}

axios(config);

}
👤Sarkar

2👍

you need to call the second request inside of .then() of the first request, which basically means to wait for the first request to finish before starting the second one:

const config = {
    method: 'post',
    url: <url1>,
    data: <data>
    headers: {
        header1: <header>
    }
}

axios(config).then((response: any) => {
    const access_token = response.data.access_token;

    const config = {
        method: 'post',
        url: <url2>,
        headers: {
            Authorization: `Bearer ${access_token}`
        }
    }
    axios(config).then(...);
}

Leave a comment