Promise.all vs await Promise.all 示例错误



我试图看到自己Promise.allawait Promise.all之间的区别。我了解到,如果其中一个承诺失败,第一个承诺会提前结束,但在同样的情况下,等待我们必须等待所有承诺的完成。

在我的示例中,在这两种情况下,它们同时完成。我做错了什么?

/**
* Create a promise
* @param ok true -> resolve, false -> reject
*/
function create_promise(ok) {
return new Promise((resolve, reject) => {
setTimeout(() => ok ? resolve() : reject(), 2e3)
})
}
// Finish as soon as I get a reject
Promise.all([create_promise(true), create_promise(false), create_promise(true)])
.catch(() => console.log('rejected'))
// Finish after waiting all
const my_async_function = async () => 
await Promise.all([create_promise(true), create_promise(false), create_promise(true)])
my_async_function().catch(() => console.log('rejected'))

await Promise.all将确保在执行await之后的行之前解析所有承诺。

/**
* Create a promise
* @param ok true -> resolve, false -> reject
*/
function create_promise(ok) {
return new Promise((resolve, reject) => {
setTimeout(() => ok ? resolve() : reject(), 2e3)
})
}
console.log("async/await version...")
const my_async_function = async () => {
console.log("before await promise.all");
const res = await Promise.all([create_promise(true), create_promise(false), create_promise(true)]);
console.log("after await  promise.all"); // This line will be executed only after all promises are successfully resolved
return res;
}
my_async_function().catch(() => console.log('rejected'))
console.log("without async/await version...")
const my_SYNC_function = () => {
console.log("before promise.all");
const res = Promise.all([create_promise(true), create_promise(false), create_promise(true)]);
console.log("after promise.all"); // This line will always be immediately executed after the Promise.all line, and not waiting for the promise completion  at all.
return res; // So this line returns the return value of Promise.all, which will be an unresolved promise because the 2 seconds have not been elapsed yet.
}

my_SYNC_function().catch(() => console.log('rejected'))

这与承诺本身以某种方式"执行得更快"无关。

但是,调用Promise.all而不await的函数更早返回,它只是返回一些尚未解析的Promise。

最新更新