SyntaxError: await is only valid in async functions, async generators and modules
当 await 表达式在 async 函数或模块或其他异步上下文之外使用时,会发生 JavaScript 异常 "await 只能在 async 函数、async 生成器和模块中使用"。
消息
SyntaxError: await is only valid in async functions and the top level bodies of modules (V8-based) SyntaxError: await is only valid in async functions, async generators and modules (Firefox) SyntaxError: Unexpected identifier (Safari)
错误类型
哪里出错了?
JavaScript 执行从不阻塞:await 永远不会阻塞程序的执行。相反,它会暂停周围异步任务的执行,同时允许其他任务继续运行。因此,await 不能在同步任务中使用,例如函数、生成器函数或脚本的顶层。当前文件是脚本还是模块并不总是很明显——有关更多信息,请参阅模块指南。
示例
顶层 await
你不能在脚本的顶层使用 await
html
<script>
await fetch("https://example.com");
// SyntaxError: await is only valid in async functions, async generators and modules
</script>
而是将脚本设为一个模块
html
<script type="module">
await fetch("https://example.com");
</script>
异步回调
你不能在同步回调中使用 await
js
urls.forEach((url) => {
await fetch(url);
// SyntaxError: await is only valid in async functions, async generators and modules
});
而是将回调设为异步。有关更多解释,请参阅使用 Promise 指南。
js
Promise.all(
urls.map(async (url) => {
await fetch(url);
}),
);