我如何知道 for 循环内的所有 Promise 何时完成执行?有更好的方法吗?
for (let index = 0; index < array.length; index++) {
request(array[index], function (error, response, body) {
promise1().then(result1 => {
if (result1 !== 0) {
promise2().then(result2 => {
promise3(result2);
}
} else {
promise3(result1);
}
});
});
}
console.log('all promises finished');
最佳答案
通过将代码转换为使用 async
/await
将项目映射到 Promise,然后使用标准 Promise.all()
等待所有 promise 解决的函数:
// promisified request()
const requestP = item =>
new Promise((resolve, reject) => {
request(item, (error, response, body) => {
if (error) return reject(error);
resolve({ response, body });
});
});
const processItem = async item => {
const { response, body } = await requestP(item);
const result1 = await promise1(/* this probably uses response or body? */);
if (result1 !== 0) {
const result2 = await promise2();
return await promise3(result2);
} else {
return await promise3(result1);
}
};
const promises = array.map(processItem);
Promise.all(promises).then(() => {
console.log("all promises finished");
});
关于node.js - 等到所有 promise 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56754301/