[英]React - Async api call, Promise.all wait for calls to finish
An api call I have returns this (general list of schedules): 一个api调用我返回这个(一般的时间表列表):
const schedules = {
data: [
{
id: "2147483610",
selfUri: "/schedules/2147483610",
type: "Schedule",
status: "Pending"
},
{
id: "2147650434",
selfUri: "/schedules/2147650434",
type: "Schedule",
status: "Pending"
}
],
These schedules won't initiate on the server until each schedule.data.selfUri
is individually requested. 在单独请求每个
schedule.data.selfUri
之前,这些计划不会在服务器上启动。 So is there a way to pull each of the selfUri's
and request each of them in a different api call? 那么有没有办法拉出每个
selfUri's
并在不同的api调用中请求每个selfUri's
?
Using Promise.all
is this the correct approach? 使用
Promise.all
这是正确的方法吗?
Promise.all(this.state.scheduleUri.map((uri) => { return axios.get(uri, ...); }));
Normally with axios
I'd do something like this: 通常使用
axios
我会做这样的事情:
axios({
method: "get",
url: `/get/data`
})
.then(response => {
console.log(response);
this.setState(
{
someState: response.data
});
})
.catch(error => console.log(error.response));
};
Yes, a combination between a single Promise and a Promise.all will do the trick. 是的, 单个Promise和Promise.all之间的组合将起到作用 。
Here's how I would approach this: 这是我如何处理这个问题:
// 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));
Sounds like a plan to me. 听起来像一个合理的计划。
You don't need to wait for all requests to finish but handle them one by one as soon as they return: 您无需等待所有请求完成,但一旦返回就会逐个处理:
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.