等待
一句话解释
等待 keyword pauses 异步 函数 直到 Promise settles, 然后 resumes 使用 resolved 值.
用大白话说
await makes asynchronous code read like synchronous code. When you write const data = await fetch(url), the function pauses at that line until the promise from fetch settles, then resumes with the resolved value assigned to data.
等待 can only be used inside 异步 functions (or at the top level in modern modules). If the awaited promise rejects, 等待 throws the error, which you can catch with a regular try/catch block — no .catch() chaining needed.
While the function is paused at an 等待, the event loop is free to run other tasks. This is why 等待 is non-blocking: your function waits, but the program does not. Other handlers, timers, and network responses keep running.
示例
async function loadUser() {
try {
const res = await fetch("/api/user");
const user = await res.json();
console.log(user);
} catch (err) {
console.error("Load failed:", err);
}
}等待 pauses 直到 每个 Promise settles. 错误 是 caught 使用 normal try/catch 块.
常见混淆
容易混淆的对象: 异步
关键区别:
等待pauses execution 内部 异步 函数 直到 Promise settles;异步declares 函数 那个 允许等待. 你 需要异步on 函数 到 use等待in 它的 请求体.
相关术语
相关资源
相关课程
- 异步 JavaScript
等待 in 深度
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。