使用 Javascript / ECMAScript 6 等待多个承诺
Await more than one promise with Javascript / ECMAScript 6
我想开始一个承诺列表,并在所有承诺完成后执行回调(没有 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/
我想开始一个承诺列表,并在所有承诺完成后执行回调(没有 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/