我有如下数组:
arr = ['res1', 'res2', 'res3'];
然后对于每个 arr
值,我将执行一个将返回 promise 的 API 调用
arr.forEach(val => this.getPromise(val));
getPromise
方法返回一个 promise 。
在我调用另一个方法之前,我需要等待所有的 promise 。我应该怎么做?
最佳答案
您可以使用 Promise.all()在所有 promise 都解决后执行操作。它需要一系列 promise :
const promises = ["val1", "val2"].map(val => this.getPromise(val));
Promise.all(promises)
.then(results => console.log(results)) // this is an array
.catch(err => console.log(err));
您可以像使用 promise 一样使用 then() 和 catch()。响应是一组解析值。
希望对您有所帮助!
关于javascript - Angular 5等待 promise 从for循环返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52509208/