【问题标题】:How to manage multiple async API calls in react如何在反应中管理多个异步 API 调用
【发布时间】:2021-10-12 05:55:58
【问题描述】:
我正在使用 AWS amplify 进行 API 调用,并且我需要进行 5 个异步 API 调用。如何有效地进行这些调用并等待所有调用完成,然后使用这些调用获得的数据开始工作流程。
【问题讨论】:
标签:
javascript
reactjs
aws-amplify
【解决方案1】:
其实我发现了,所以就在这里……
load1 = async () => {
return API.get('myApi', '/myapi1', {})
}
load2 = async () => {
return API.get('myApi', '/myapi2', {})
}
verifyTasksExecution = async () => {
Promise.all([this.load1(),this.load2()]).then((values) => {
console.log('VALUES:', values);
});
}
【解决方案2】:
要等待多个承诺并等待所有承诺解决,您可以使用Promise.all,它接受一组承诺并返回一组已解决的数据
您可以在MDN 中阅读更多相关信息,以下示例来自 MDN
// this will be counted as if the iterable passed is empty, so it gets fulfilled
var p = Promise.all([1,2,3]);
// this will be counted as if the iterable passed contains only the resolved promise with value "444", so it gets fulfilled
var p2 = Promise.all([1,2,3, Promise.resolve(444)]);
// this will be counted as if the iterable passed contains only the rejected promise with value "555", so it gets rejected
var p3 = Promise.all([1,2,3, Promise.reject(555)]);
// using setTimeout we can execute code after the stack is empty
setTimeout(function() {
console.log(p);
console.log(p2);
console.log(p3);
});
// logs
// Promise { <state>: "fulfilled", <value>: Array[3] }
// Promise { <state>: "fulfilled", <value>: Array[4] }
// Promise { <state>: "rejected", <reason>: 555 }
【解决方案3】:
您可以使用promise.all 异步发出所有请求。详情请见this question
还要注意,如果任何请求失败,则 promise.all 会拒绝。
【解决方案4】:
假设您使用的是 JavaScript,听起来您需要的是 Promise.all()
call1 = axios(/* api request */)
call2 = axios()
call3 = axios()
call4 = axios()
call5 = axios()
Promise.all(call1, call2, call3, call4, call5).then(results => {
// Do work here
call1Result = results[0]
call2Result = results[1]
etc..
});