我试图让自己看到Promise.all和await 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'))
发布于 2020-06-01 21:05:05
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'))
这与承诺本身被以某种方式“更快地执行”无关。
然而,调用不带await的Promise.all的函数返回得更早,它只是返回了一些尚未解决的承诺。
https://stackoverflow.com/questions/62131616
复制相似问题