语法错误:wait 仅在异步函数、异步生成器和模块中有效

当在 异步函数modules 或其他异步上下文之外使用 await 表达式时,会发生 JavaScript 异常 "wait 仅在异步函数、异步生成器和模块中有效"。

¥The JavaScript exception "await is only valid in async functions, async generators and modules" occurs when an await expression is used outside of async functions or modules or other async contexts.

信息

¥Message

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)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

JavaScript 执行永远不会阻塞:await 永远不会阻止程序的执行。相反,它会暂停周围异步任务的执行,同时允许其他任务继续运行。因此,await 不能用于同步任务,例如函数、生成器函数或顶层脚本。当前文件是脚本还是模块并不总是显而易见的 - 有关更多信息,请参阅 模块指南

¥JavaScript execution is never blocking: an await can never block the execution of the program. Instead, it pauses the execution of the surrounding async task, while allowing other tasks to continue running. Therefore, await cannot be used in sync tasks, such as functions, generator functions, or top level of scripts. It is not always apparent whether the current file is a script or a module — see the Modules guide for more information.

示例

¥Examples

顶层等待

¥Top-level await

你不能在脚本的顶层使用 await

¥You cannot use await at the top level of a script:

html
<script>
  await fetch("https://example.com");
  // SyntaxError: await is only valid in async functions, async generators and modules
</script>

相反,使脚本成为一个模块:

¥Instead, make the script a module:

html
<script type="module">
  await fetch("https://example.com");
</script>

异步回调

¥Async callbacks

你不能在同步回调中使用 await

¥You cannot use await in a sync callback:

js
urls.forEach((url) => {
  await fetch(url);
  // SyntaxError: await is only valid in async functions, async generators and modules
});

相反,使回调异步。请参阅 使用 promise 指南 中的更多说明。

¥Instead, make the callback async. See more explanation in the Using promises guide.

js
Promise.all(
  urls.map(async (url) => {
    await fetch(url);
  }),
);

也可以看看

¥See also