javascript - 调用内部有 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
. 如果我使用await
for 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
它们全部提升到函数阶梯上。
希望有人可以为我澄清这一点。谢谢你。
解决方案
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
每个异步函数都会返回一个 Promise,并且它将“向上链”直到第一次调用。
如果你真的想要的话,有一些库旨在从 Promise 中进行同步调用。
但问题是:这就是 javascript 的工作原理
推荐阅读
- node.js - 在 React 中安装依赖项
- html - 使用图像作为拇指 HTML/CSS 制作滚动条
- android - 当适配器上的项目非零时,Firebase 添加新子项
- python - 在 SQL/Python 中使用动态日期值透视雪花查询
- google-cloud-platform - `capture_tpu_profile` 无法访问 TPU
- java - 获取消息的当前可见性超时
- java - Java 和 Dart 之间如何通过 Socket 进行通信
- regex - 正则表达式在没有特定模式时选择特定单词?
- excel - VBA - 组合框向下滚动条损坏
- xml - XSLT 用每个标签的计数在 XML 中转换一些标签