簡體   English   中英

React - 異步api調用,Promise.all等待調用完成

[英]React - Async api call, Promise.all wait for calls to finish

一個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調用中請求每個selfUri's

使用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));
};

是的, 單個PromisePromise.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));

聽起來像一個合理的計划。

您無需等待所有請求完成,但一旦返回就會逐個處理:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM