我进行的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));
};
答案 0 :(得分:2)
是的,将单个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));
听起来像我的计划。
答案 1 :(得分:1)
您无需等待所有请求完成,而是在请求返回时一一处理它们:
axios.get('/get/schedules')
.then(response => {
const schedules = response.data;
schedules.forEach(schedule =>
axios.get(schedule.selfUri)
.then(responseArray => {
this.setState({
....
})
});
)
})