【发布时间】: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。如果我使用await 为method2() 调用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