首页 > 解决方案 > 调用内部有 await 的方法,不等待 promise 解决

问题描述

考虑这样的场景:

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. 如果我使用awaitfor method2()call in method3(),它可以工作:

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

即使在阅读了这么多博客文章、Mozilla 文档和 stackoverflow 答案之后,我也无法真正理解 await/async 是如何工作的。

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

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

标签: javascripttypescriptasync-await

解决方案


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

每个异步函数都会返回一个 Promise,并且它将“向上链”直到第一次调用。

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

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


推荐阅读