admin管理员组文章数量:1276735
I am wanting to do something like the following in a React ponent:
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
var results = []
someArray.forEach(function(item) {
var result = someAsyncFunctionThatReturnsAPromise(item);
results.push(result);
});
$q.all(results).then(function() {
// do something
});
I am wanting to do something like the following in a React ponent:
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
var results = []
someArray.forEach(function(item) {
var result = someAsyncFunctionThatReturnsAPromise(item);
results.push(result);
});
$q.all(results).then(function() {
// do something
});
Share
Improve this question
asked Oct 20, 2017 at 20:41
dfritchdfritch
3591 gold badge3 silver badges16 bronze badges
8
-
3
use
Promise.all(/* Your Promise Array */).then(...)
? – CRice Commented Oct 20, 2017 at 20:42 -
You're making your code synchronous, so isn't the order of operations guaranteed? Meaning that if you put
console.log(results)
after your forEach loop, it would have all the values. That's the beauty of async/await. – Chase DeAnda Commented Oct 20, 2017 at 20:45 - 1 @ChaseDeAnda Unfortunately you can't use forEach with async / await, but a basic for loop will work.. – Keith Commented Oct 20, 2017 at 20:47
- @Keith Ah, okay thanks I didn't know that. OP check out this post stackoverflow./questions/37576685/… – Chase DeAnda Commented Oct 20, 2017 at 20:48
-
As @CRice said but you will have to remove the
async
await
– Kevin Farrugia Commented Oct 20, 2017 at 20:51
2 Answers
Reset to default 7You'd do exactly the same thing as if it wasn't a React ponent:
Promise.all(someArray.map(someAsyncFunction)).then(results => {
// do stuff with results
});
Of course you can also use q
, which $q
is based on. It's up to you.
In addition to the answer from Felix, inside an async
function, you can also await
on the results from Promise.all()
, so:
const results = await Promise.all(someArray.map(someAsyncFunction));
本文标签: javascriptHow to await multiple async await requests in ReactStack Overflow
版权声明:本文标题:javascript - How to await multiple async await requests in React - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741261677a2367737.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论