Реакция - Асинхронный вызов API, Promise.all ждут завершения вызовов - PullRequest
0 голосов
/ 06 декабря 2018

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 голосов
/ 06 декабря 2018

Вам не нужно ждать завершения всех запросов, но обрабатывайте их один за другим, как только они возвращаются:

axios.get('/get/schedules')
  .then(response => {
    const schedules = response.data;
    schedules.forEach(schedule => 
      axios.get(schedule.selfUri)
      .then(responseArray => {
          this.setState({
              ....
          })
      });
    )
  })
0 голосов
/ 06 декабря 2018

Да, комбинация между одиночным 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));

Для меня звучит как план.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...