异步
一句话解释
异步 keyword declares 函数 那个 总是 返回 Promise, 启用 等待 内部 它.
用大白话说
async keyword marks 函数 as asynchronous. 异步函数总是返回 Promise — 如果你 返回 plain 值, JavaScript wraps 它 in resolved Promise automatically. 真实 power 的 async 是那个它 lets 你 use await inside the function body.
Before 异步/等待, asynchronous code used nested callbacks or promise chains. With 异步, you can write async code that reads top-to-bottom like synchronous code, while still being non-blocking. The event loop keeps running while your function waits.
Marking a function 异步 does not make it run on a separate thread — JavaScript is single-threaded. It only changes how the function's return value is wrapped and enables 等待. The actual concurrency comes from the underlying APIs (fetch, timers, etc.).
示例
async function getUser(id) {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user;
}
getUser(42).then((user) => console.log(user));异步 lets 你 use 等待 内部. 函数 返回 Promise 那个 resolves 使用 用户.
常见混淆
容易混淆的对象: 等待
关键区别:
异步declares 函数 那个 返回 Promise;等待pauses execution 内部 异步 函数 直到 Promise settles. 你 use 它们 together: 异步 启用 等待.
相关术语
相关资源
相关课程
- 异步 JavaScript
异步/等待 in 深度
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。