'await' expressions are only allowed within async functions and at the top levels of modules.
时间: 2024-12-28 14:34:11 浏览: 6
"await" expressions indeed have a specific context in JavaScript. They can only be used inside an `async` function[^1] because they signify that the code following it should pause execution until the associated Promise completes. Here's an example:
```javascript
// 示例:异步函数中使用await
async function getDataFromAPI() {
try {
const response = await fetch('https://api.example.com/data');
if (response.ok) {
const data = await response.json();
// 这里的代码将在fetch成功并解析JSON后运行
console.log(data);
} else {
throw new Error('Failed to fetch data');
}
} catch (error) {
console.error(error);
}
}
getDataFromAPI(); // 等待Promise解析后再执行后续代码
```
In the case of module top-levels[^2], you can use `async` functions there as well, but note that any `export` statements must come after all `await` expressions, since they must be able to evaluate without awaiting promises.
阅读全文