Promise 状态pending 单向流转到 fulfilled / rejected
pending fulfilled rejected then catch 状态单向流转,不可逆

回调函数能传递异步结果,但多层嵌套之后,代码会变成横向的「回调地狱」。Promise 把「未来的结果」对象化,可以链式组合。

三种状态

pending(进行中)→ fulfilled(成功)或 rejected(失败)。状态一旦改变就不可逆,这正是它比回调更可靠的地方。

function fetchUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => (id > 0 ? resolve({ id, name: 'u' + id }) : reject(new Error('bad id'))), 300)
  })
}
fetchUser(1).then((u) => console.log(u)).catch((e) => console.error(e))

组合多个异步

  • Promise.all:全部成功才成功,任一失败即失败,结果是数组。
  • Promise.race:谁先完成用谁,常用来做超时。
  • Promise.allSettled:等所有都落定,不因单个失败中断。

async/await

async 函数返回 Promise;await 让后续代码等到结果再执行。错误处理用 try...catch,比 .then 的第二个参数更自然。

async function load(id) {
  try {
    const user = await fetchUser(id)
    return user
  } catch (e) {
    console.error('加载失败', e)
  }
}