React-异步api调用Promise.all等待调用完成

时间:2018-12-05 21:06:28

标签: javascript reactjs promise

我进行的api调用返回此消息(日程表的常规列表):

const schedules = {
  data: [
    {
      id: "2147483610",
      selfUri: "/schedules/2147483610",
      type: "Schedule",
      status: "Pending"
    },
    {
      id: "2147650434",
      selfUri: "/schedules/2147650434",
      type: "Schedule",
      status: "Pending"
    }
  ],

在单独请求每个schedule.data.selfUri之前,这些计划不会在服务器上启动。 那么,有没有办法拉出每个selfUri's并在不同的api调用中请求它们呢?

使用Promise.all是正确的方法吗?

Promise.all(this.state.scheduleUri.map((uri) => { return axios.get(uri, ...); }));

通常使用axios我会做这样的事情:

axios({
  method: "get",
  url: `/get/data`
})
.then(response => {
    console.log(response);
    this.setState(
      {
        someState: response.data
      });
  })
  .catch(error => console.log(error.response));
};

2 个答案:

答案 0 :(得分:2)

是的,将单个Promise Promise.all 结合使用即可达到目的。

这是我的处理方式:

// Step 1: get your schedules list.
axios.get('/get/schedules')
  .then(response => {
    const schedules = response.data;

    // Step 2: get each of your schedules selfUri data.
    // This line gets called after the schedule list is received
    // However, Promise.all executes all calls asynchroniously, at once.
    return Promise.all(schedules.map(schedule => axios.get(schedule.selfUri)));
  }
  .then(responseArray => {
    // Step 3: Finally, here you have available
    // the responses from the Promise.all call in Step 2.
    // Or in other words, responseArray holds the response
    // for each of the selfUri calls.

    this.setState({
      // do whatever you want with the data ;-)
    })
  })
  .catch(error => console.log(error.response));

听起来像我的计划。

答案 1 :(得分:1)

您无需等待所有请求完成,而是在请求返回时一一处理它们:

axios.get('/get/schedules')
  .then(response => {
    const schedules = response.data;
    schedules.forEach(schedule => 
      axios.get(schedule.selfUri)
      .then(responseArray => {
          this.setState({
              ....
          })
      });
    )
  })