Promise 是对异步操作最终结果的封装,本质是一个状态机:有 pending、fulfilled、rejected 三种状态,状态一旦落定不可逆。通过 .then 注册回调,回调按微任务调度执行;链式调用时每次 then 返回新 Promise,从而解决回调地狱。resolve 时若传入另一个 Promise,会「吸收」其状态,这是 Promise/A+ 规范中 thenable 解析的核心逻辑。
async/await 是建立在 Promise 之上的语法糖:async 函数总是返回 Promise;await 暂停当前函数执行,等待 Promise 落定,其后续代码相当于放入 .then 回调(微任务)。它让异步代码写成同步的线性结构,且可用 try/catch 统一捕获错误。
async function load() {
try {
const user = await fetchUser();
console.log(user);
} catch (e) { /* 捕获 rejected */ }
}
易错点:多个互不依赖的 await 串行执行会浪费时间,应改用 Promise.all 并发;async 函数内部抛错等价于返回 rejected Promise。追问:手写 Promise、Promise.all/race/allSettled 的区别。