如何等待多个异步等待中的请求作出反应
问题描述:
我想这样做在一个阵营组成如下:如何等待多个异步等待中的请求作出反应
const someArray = [/*stuff*/]
const results = []
someArray.forEach(async item => {
const result = await someAsyncFunction(item)
results.push(result)
})
我怎么能知道什么时候所有的结果都返回,然后做一些事情?
如果我是用$ Q,在AngularJS,我可以做
var results = []
someArray.forEach(function(item) {
var result = someAsyncFunctionThatReturnsAPromise(item);
results.push(result);
});
$q.all(results).then(function() {
// do something
});
答
除了来自菲利克斯答案,一个async
函数里,你也可以await
从Promise.all()
的结果,所以:
const results = await Promise.all(someArray.map(someAsyncFunction));
使用'Promise.all(/ *你的诺言阵列* /)。然后(...)'? – CRice
你让你的代码同步,所以不是保证操作的顺序?这意味着如果你在forEach循环之后放置'console.log(results)',它将包含所有的值。这是异步/等待的美妙之处。 –
@ChaseDeAnda不幸的是,你不能使用forEach与异步/ await,但基本的循环将工作.. – Keith