2017-10-20 222 views
1

我想这样做在一个阵营组成如下:如何等待多个异步等待中的请求作出反应

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 
}); 
+3

使用'Promise.all(/ *你的诺言阵列* /)。然后(...)'? – CRice

+0

你让你的代码同步,所以不是保证操作的顺序?这意味着如果你在forEach循环之后放置'console.log(results)',它将包含所有的值。这是异步/等待的美妙之处。 –

+1

@ChaseDeAnda不幸的是,你不能使用forEach与异步/ await,但基本的循环将工作.. – Keith

回答

4

你会做同样的事情,如果它不是一个阵营组成:

Promise.all(someArray.map(someAsyncFunction)).then(results => { 
    // do stuff with results 
}); 

中当然你也可以使用q,其中$q是基于。随你便。

+0

谢谢。我结束了使用q库。 – dfritch

0

除了来自菲利克斯答案,一个async函数里,你也可以awaitPromise.all()的结果,所以:

const results = await Promise.all(someArray.map(someAsyncFunction));