Making 2 sequential requests with Axios - second request depends on the response of 1st

Viewed 13262

The following code is not waiting for the else part to return data before resolving.

Where I'm going wrong with this code?

return request.get(`${<URL1>}`)
.then((res) => {
    if (res1.data[0]) {
        data1 = res.data[0]};
    } else {
        request.get(`${<URL2>`)
            .then((res2) => {
                data1 = res2.data
            });
    }
    return Promise.resolve(data1);
})

Thanks in advance.

San

4 Answers

That is because you're doing it wrong :)

When the program execution encounters an 'async' operation (making a network request with axios), it schedules the task and continues execution of the following lines of code. This include any return statements.

Your return should appear in the 'then' clause:

return request.get(`${<URL1>}`)
    .then((res1) => {
        if (res1.data[0]) {
            data1 = res1.data[0]
            return Promise.resolve(data1);
        } else {
            request.get(`${<URL2>`)
                .then((res2) => {
                    data1 = res2.data
                    return Promise.resolve(data1);
                });
        }
    });

Hope this helps...

Clinton.

I think you can do something like

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));

I think it should help. You can read more here

you can use async and await here, something like this:

 async function getData() {
      const firstRequest = await axios.get(`${<URL1>}`);
      data1 = firstRequest.data[0];
      if (!data1){
          const secondRequest = await axios.get(`${<URL2>}`);
          data1 = secondRequest.data;
      }
      return data1;
  }

here is how I fired a list of requests based on values returned by the first request, then add that data to the first request, then return that.

In my example, I get a list of events, then each event has an id(retrieved from first axios.get) which I need to get the event description with a subsequent axios.get, but this is the only additional data I need to get for each event, so I just replace each event short description in the event list with the long description from the subsequent axios.get

async function getEvents() {
  const events = await axios
      .get(
          eventsUrl,
          config
      )
      .then(res => {
          if (res.status === 200) {
              let events = res.data.events.filter(
                  event => event.status === 'live' || 'completed'
              )
              events.map(event => {
                  event.urlPath = event.name.text.replace(/\s+/g, '-').toLowerCase()
              })
              return events
          }
      })
      .then(async events => {
          const promises = await events.map(event => axios.get(
              `https://www.eventbriteapi.com/v3/events/${event.id}/description`,
              config
          ))
          await Promise.all(promises)
              .then(values => {
                  return events.forEach((event, index) => {
                      event.description.html = values[index].data.description.replace(`<div>${event.description.text}</div>\n`, '')
                      console.log(event.description.text)
                  })
              })
          return events
      })
      .catch(err => {
          console.log(err)
      })
    return await events
}
Related