我想要开始一个承诺列表,并在所有承诺完成时执行回调函数(不使用async/await)。
我想要开始一个承诺列表,并在所有承诺完成时执行回调函数(不使用async/await)。
我刚刚想到一个方法,只需要使用Promise.all:
function x(timeout) {
return new Promise((resolve, reject) => {
setTimeout(function() {
resolve(timeout + ' done!');
}, timeout);
});
}
(function() {
Promise.all([
x(300),
x(200),
x(100),
]).then(([x300, x200, x100]) => {
console.log(x100);
console.log(x200);
console.log(x300);
});
})();
是的,Promise.all 在这里是你的好朋友。
Promise.all([promise1, promise2]).then(([result1, result2]) => {})
有什么原因你不使用async/await,我发现它真的简化了这种模式?
const [result1, result2] = await Promise.all([promise1, promise2])
https://www.dalejefferson.com/blog/async-await-promise-all-array-destructuring/