首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Promise.all vs等待Promise.all示例错误

Promise.all vs等待Promise.all示例错误
EN

Stack Overflow用户
提问于 2020-06-01 19:55:10
回答 1查看 228关注 0票数 2

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

在我的示例中,在两种情况下,它们都是同时完成的。我哪里做错了?

代码语言:javascript
复制
/**
 * 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'))

EN

回答 1

Stack Overflow用户

发布于 2020-06-01 21:05:05

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

代码语言:javascript
复制
/**
 * 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'))

这与承诺本身被以某种方式“更快地执行”无关。

然而,调用不带awaitPromise.all的函数返回得更早,它只是返回了一些尚未解决的承诺。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62131616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档