【问题标题】:await Promise.all not waiting despite async wrapper尽管有异步包装器,但等待 Promise.all 不等待
【发布时间】:2020-03-05 21:56:05
【问题描述】:

即使在阅读了几个类似问题的答案(例如 thisthat)之后,我仍然不明白为什么这段代码不等待承诺并因此记录 ['check2'] 最后在其他检查站之后。

这是一个使用代码from this guide 的最小示例。在原始代码中,我需要先从不同来源获取一些信息,然后我的快速服务器才能开始收听。

console.log("check1");

const resolveInTwoSeconds = () => {
  return new Promise((resolve) => {
    setTimeout(() => resolve("check2"), 2000);
  })
};
async function test() {
  const asyncFunctions = [
    resolveInTwoSeconds()
  ];
  const results = await Promise.all(asyncFunctions);
  console.log(results);

}
(async() => await test())();
console.log("check3");

编辑: 想象一下“check3”是很多依赖于 test() 副作用的代码。 因此,我希望它在 check2 打印后运行。 但是我在这里使用 await,所以 我不必更改或移动“check3”

【问题讨论】:

  • 它应该按预期工作,并在 2 秒后记录 check2
  • 如果您希望 "check3" 最后记录,您应该在最后一个异步 IIFE 中添加该语句 within
  • 你能否描述你的问题,测试你的代码和工作发现在 Promise.all 方面
  • @EugenSunic "...为什么这段代码...记录 ['check2'] 在其他检查点之后。" - 预期输出:check 1 -> check 2 -> check 3。实际输出:check1 -> check 3 -> check 2
  • async / await 只是 Promise 和 .then() 的语法糖。任何不在.then() 调用中的东西(在await 之后的函数调用中)都不会“等待”。

标签: javascript async-await


【解决方案1】:

这行代码声明了一个async函数并执行它:

(async() => await test())();

到目前为止,没有任何东西等待它的结果,并且执行继续到console.log("check3")

你必须明确地等待它:

await (async () => await test())();

现在,这还不行,因为顶层函数不是async。每当您需要调用await 时,您必须确保在async 函数中调用它。一种方法是将所有内容包装在另一个 async 函数中:

(async () => {
  console.log("check1");

  const resolveInTwoSeconds = () => {
    return new Promise((resolve) => {
      setTimeout(() => resolve("check2"), 2000);
    })
  };
  async function test() {
    const asyncFunctions = [
      resolveInTwoSeconds()
    ];
    const results = await Promise.all(asyncFunctions);
    console.log(results);

  }
  await (async ()=> await test())();
  console.log("check3");
})()

否则,按照其他人的建议,将您的 check3 移动到您已有的 async 函数中。

【讨论】:

  • 好的,谢谢大家。这意味着如果不触摸“检查 3”(将其移入包装函数或使用回调),这是不可能的。
【解决方案2】:

这应该做你想做的事。您需要将 console.log 放在异步函数中。

console.log("check1");

const resolveInTwoSeconds = () => {
  return new Promise((resolve) => {
    setTimeout(() => resolve("check2"), 2000);
  })
};
async function test() {
  const asyncFunctions = [
    resolveInTwoSeconds()
  ];
  const results = await Promise.all(asyncFunctions);
  console.log(results);

}
(async() =>{ 
    await test();
    console.log("check3");
})();

【讨论】:

  • 将应该是 check3 的代码移动到一个函数中并在测试后调用它,这是我能想到的唯一解决方案@Robin。
猜你喜欢
  • 2018-02-07
  • 2016-07-07
  • 2016-03-25
  • 2017-10-09
  • 2018-10-01
  • 1970-01-01
  • 2017-12-11
相关资源
最近更新 更多