I am wanting to do something like the following in a React component:
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
});
You'd do exactly the same thing as if it wasn't a React component:
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.
除了Felix的答案,在async
函数中,你还可以await
Promise.all()
的结果,所以:
const results = await Promise.all(someArray.map(someAsyncFunction));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.