【发布时间】:2019-07-23 20:22:53
【问题描述】:
我正在阅读一个包含以下示例代码的博客,
async function fAsync() {
// actual return value is Promise.resolve(5)
return 5;
}
// can't call "await fAsync()". Need to use then/catch
fAsync().then(r => console.log(`result is ${r}`));
在博客中提到了这一点,
如果我们从普通函数或全局范围内调用异步函数,我们将无法使用 await,而是求助于原版 Promise:
我的困惑是为什么我们不能在那里使用 await?博文是https://nikgrozev.com/2017/10/01/async-await/
【问题讨论】:
-
为了获得有效的异步等待语法和功能,还需要在异步函数中调用 await 关键字。如果你在异步函数中有整个代码块,你可以等待 fAsync() 的结果。 jsfiddle.net/gmsx42ny
-
await 仅适用于标记为 async 的函数,这就是为什么你不能在异步函数块之外使用它需要使用 then/catch
-
阅读mdn documentation的第一行
标签: javascript