Axios随机数量的请求

时间:2018-05-14 13:48:24

标签: javascript reactjs http react-native axios

我需要向Axios发出多个请求,但我不知道有多少,请求的数量是完全随机的,可能是0或1或9182379,完成后我需要做一些事情,好像现在一样我必须更新我的状态(对象数组)。

你知道我怎么能这样做?

let oldTickets = [...this.state.playedTickets];
let length = oldTickets.length;
let newTickets = [];

for (let index = 0; index < length; index++) {
  let currentTicket = oldTickets[index];

  // just imported function that returns axios.get call
  checkTickets(currentTicket.ticketNumber)
    .then(data => {

      let newTicket = {
        bla: bla
      }

      newTickets.push(newTicket);
      this.setState({playedTickets: newTickets})

    })
    .catch(err => {
      console.log(err);
    })

}

这很好但我知道它不好,所以我正在寻找更好的解决方案!

1 个答案:

答案 0 :(得分:0)

  

完成所有工作后我需要做点什么

您可以将数组映射到promises并使用Promise.all

Promise.all( // executes all requests in parallel
  this.state.playedTickets.map(({ ticketNumber }) => checkTickets(ticketNumber))
).then(playedTickets => { // or declare function as `async` and use `await`
  // executed only after all requests resolved
  console.log('tickets', playedTickets); 
  this.setState({ playedTickets });
}).catch(e => console.log(e)); // executed as soon as one request fails

修改

  

继续等待所有请求,即使有些失败,并根据成功请求的结果设置状态

要实现这一点,只需在传递给Promise.all之前捕获错误:

Promise.all(
  this.state.playedTickets.map(({ ticketNumber }) =>
    checkTickets(ticketNumber).catch(console.log)
  )
).then(playedTickets => {
  console.log('tickets', playedTickets);
  this.setState({ playedTickets });
});

失败的请求将undefined作为数组中的值 如果需要,您可以使用

过滤掉它们
const validTickets = playedTickets.filter(ticket => ticket !== undefined)