[英]How to await multiple async await requests in React
I am wanting to do something like the following in a React component: 我想在React组件中执行以下操作:
const someArray = [/*stuff*/]
const results = []
someArray.forEach(async item => {
const result = await someAsyncFunction(item)
results.push(result)
})
How can I know when all the results have returned then do something? 我怎么知道所有结果何时返回然后做某事?
If I was using $q, in AngularJS, I could do 如果我在AngularJS中使用$ q,我可以做到
var results = []
someArray.forEach(function(item) {
var result = someAsyncFunctionThatReturnsAPromise(item);
results.push(result);
});
$q.all(results).then(function() {
// do something
});
除了Felix的答案,在async
函数中,你还可以await
Promise.all()
的结果,所以:
const results = await Promise.all(someArray.map(someAsyncFunction));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.