async/await是基于Promise的语法糖,使异步代码更直观;async函数自动返回Promise,await在async内暂停执行并等待Promise完成,支持错误捕获且不阻塞线程。
async/await 是 JavaScript 中处理异步操作的语法糖,本质是基于 Promise 的封装,让异步代码写起来像同步代码一样直观。 它不会改变异步的本质,但大幅简化了 Promise 链式调用和错误处理的写法。
在函数声明前加 async,该函数就变成异步函数。它会自动把返回值包装成 Promise:
return 42),实际返回的是 Promise.resolve(42)
throw new Error()),等价于返回 Promise.reject(...)
await 只能在 async 函数内部使用。 它会让 JS 引擎暂停当前 async 函数的执行,等待右侧表达式(必须是 Promise 或 thenable)完成(fulfilled 或 rejected),然后继续执行:
await promise 的结果就是 promise.then(value => value) 中的 value
ejected),await 会抛出错误,可以用 try...catch 捕获await 不会阻塞整个线程,只是暂停当前 async 函数;其他任务(如事件、定时器)仍可正常运行对比传统 Promise 写法与 async/await:
// Promise 风格
fetch('/api/data')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
// async/await 风格
async function getData() {
try {
const res = await fetch('/api/data');
const data = await res.json();
console.log(data);
} catch (err) {
console.error(err);
}
}
await 会自动对非 Promise 值调用 Promise.resolve():
await 123 等价于 await Promise.resolve(123),立即得到 123
await { then() { ... } }(thenable 对象)也会被当作 Promise 处理await null、await undefined 也合法,它们会被转为 Promise.resolve(null) 等不复杂但容易忽略:await 后面不是 Promise 也能用,但真正有意义的等待,还是得靠真正的异步 Promise。