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);
}),
);