Axios随机请求数 [英] Axios random number of requests
问题描述
我需要使用Axios发出多个请求,但我不知道有多少个,请求的数量完全是随机的,可能是0或1或9182379,在全部完成之后,我需要做一些事情,就像现在我必须更新状态(对象数组).
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).
您知道我该怎么做吗?
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.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
即使某些请求失败,也继续等待所有请求,并根据成功请求的结果设置状态
continue awaiting for all requests even if some failed, and set the state based on the results of the successful requests
要实现此目的,只需在传递给Promise.all
之前捕获错误:
To achieve this, simply catch the error before passing to Promise.all
:
Promise.all(
this.state.playedTickets.map(({ ticketNumber }) =>
checkTickets(ticketNumber).catch(console.log)
)
).then(playedTickets => {
console.log('tickets', playedTickets);
this.setState({ playedTickets });
});
失败的请求将以undefined
作为数组中的值.
如果需要,您可以使用
Failed requests will have undefined
as the value in the array.
If required, you can filter them out with
const validTickets = playedTickets.filter(ticket => ticket !== undefined)
这篇关于Axios随机请求数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!