我想在 React 组件中执行如下操作:
const someArray = [/*stuff*/]
const results = []
someArray.forEach(async item => {
const result = await someAsyncFunction(item)
results.push(result)
})
我怎么知道什么时候所有的结果都返回然后做些什么?
如果我在 AngularJS 中使用 $q,我可以这样做
var results = []
someArray.forEach(function(item) {
var result = someAsyncFunctionThatReturnsAPromise(item);
results.push(result);
});
$q.all(results).then(function() {
// do something
});
最佳答案
如果它不是 React 组件,你会做同样的事情:
Promise.all(someArray.map(someAsyncFunction)).then(results => {
// do stuff with results
});
当然你也可以用q
, $q
基于。这取决于你。
关于javascript - 如何在 React 中等待多个异步等待请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46857023/