admin管理员组

文章数量:1338956

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

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

Share Improve this question edited Apr 29, 2021 at 7:07 Dhia Djobbi 1,2862 gold badges20 silver badges37 bronze badges asked Nov 17, 2017 at 4:18 kalladakallada 1,9296 gold badges38 silver badges72 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

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 includes 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!

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;
  }

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 plete
  }));

I think it should help. You can read more here

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' || 'pleted'
              )
              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./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
}

本文标签: