简体   繁体   English

Axios随机请求数

[英]Axios random number of requests

I need to make multiple requests with Axios but I dont know how many, the number of requests is totally random and it could be 0 or 1 or 9182379, and after they are all done I need to do something, as if now I have to update my state(array of objects). 我需要使用Axios发出多个请求,但我不知道有多少个,请求的数量是完全随机的,可能是0或1或9182379,在完成所有操作后,我需要做一些事情,好像现在我必须更新我的状态(对象数组)。

Do you have any idea how could I do this ?? 你有什么主意我该怎么做吗?

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

}

This is working fine but I know it's not good, so I am searching for better solution! 这个工作正常,但我知道这不好,所以我正在寻找更好的解决方案!

after they are all done I need to do something 他们都做完之后我需要做点什么

You can map the array to promises and use Promise.all : 您可以将数组映射到promise并使用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

EDIT: 编辑:

continue awaiting for all requests even if some failed, and set the state based on the results of the successful requests 即使某些请求失败,也继续等待所有请求,并根据成功请求的结果设置状态

To achieve this, simply catch the error before passing to Promise.all : 为此,只需在传递给Promise.all之前捕获错误:

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

Failed requests will have undefined as the value in the array. 失败的请求将undefined为数组中的值。
If required, you can filter them out with 如果需要,您可以使用

const validTickets = playedTickets.filter(ticket => ticket !== undefined) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM