【问题标题】:Calling a method that has an await inside, does not wait for the promise to resolve调用内部有 await 的方法,不等待 promise 解决
【发布时间】:2021-09-08 10:20:30
【问题描述】:

考虑这样一个场景:

function method1(): Promise<string> {
  return new Promise((resolve, reject) => {
    // do something
    const response = true;
    setTimeout(() => {
      if (response) {
        resolve("success");
      } else {
        reject("error");
      }
    }, 5000);
  });
}

async function method2(): Promise<string> {
  const result = await method1();
  // do some other processing and return a different result
  const result2 = result + "1";
  return result2;
}

function method3(): void {
  console.log("test 1");
  const result = method2();
  console.log("test 2");
}

method3();

我不确定为什么method2() 不会等待结果,因为它包含await。如果我使用awaitmethod2() 调用method3(),它可以工作:

async function method3(): Promise<string> {
  console.log("test 1");
  const result = await method2();
  console.log("test 2");
}

即使阅读了这么多博文、Mozilla 文档和 stackoverflow 答案,我也无法真正理解 await/async 的工作原理。

其中一位 cmets 说“你无法摆脱异步”。并进一步解释说,由于任何异步函数都会返回一个 Promise,因此必须 await 将它们全部提升到函数阶梯上。

希望有人可以为我澄清这一点。谢谢。

【问题讨论】:

  • 你没有使用await来调用async函数。
  • 是的,我知道该怎么做才能“修复”它。我不明白背后的原因。例如,您必须等待所有异步功能吗? method1() 返回一个由 method2() 等待的承诺。所以我假设当你打电话给method2()时,它会自动等待method1()

标签: javascript typescript async-await


【解决方案1】:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

每个异步函数都会返回一个 Promise,并且会在第一次调用之前“上链”。

如果你真的想要的话,有一些库旨在从 Promise 中进行同步调用。

但问题是:这就是 javascript 的工作原理

【讨论】:

【解决方案2】:
  • 将异步函数标记为async
  • 等待异步函数的函数本身就是异步的
  • 在调用异步函数时等待它们(如果您需要结果来继续执行),但在顶层除外,您可以使用等效的 then 语法

async function method1() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(1), 5000);
  });
}

async function method2() {
  console.log("starting method 2");
  const result = await method1();
  console.log("finished method 2");
  return result + 1
}

async function method3() {
  console.log("starting method 3");
  const result = await method2();
  console.log("finished method 3");
  return result + 1
}

method3().then(result => console.log(result))

【讨论】:

    猜你喜欢
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多