悉野小楼

导航

promise原理

Promise 的本质可以概括为一句话:
Promise 是一个“异步任务的状态容器 + 回调队列管理器”
它并不让异步变成同步,而是把“未来才会知道的结果”抽象成一个对象,让你可以用统一的方式去处理成功、失败和链式调用。
 

一、Promise 最核心的思想

Promise 围绕三点:
  1. 状态机(三种状态)
  2. 保存异步结果(值 / 原因)
  3. 收集回调,并在合适时机统一触发

二、Promise 的三种状态

 
pending  (进行中)
   │
   ├── fulfilled(成功)── 带 value
   └── rejected (失败)── 带 reason
 
 
关键规则:
  • 初始状态:pending
  • 一旦从 pending → fulfilled / rejected状态不可再改变
  • 同一个 Promise 永远不会同时触发 thencatch

三、Promise 内部“大概长什么样”(原理级结构)

用一个简化模型理解(非源码):
 
class Promise {
  constructor(executor) {
    this.state = 'pending'
    this.value = undefined
    this.reason = undefined

    this.onFulfilledCallbacks = []
    this.onRejectedCallbacks = []

    const resolve = (value) => {
      if (this.state !== 'pending') return
      this.state = 'fulfilled'
      this.value = value
      this.onFulfilledCallbacks.forEach(fn => fn())
    }

    const reject = (reason) => {
      if (this.state !== 'pending') return
      this.state = 'rejected'
      this.reason = reason
      this.onRejectedCallbacks.forEach(fn => fn())
    }

    try {
      executor(resolve, reject)
    } catch (err) {
      reject(err)
    }
  }
}
 
 
核心点:
  • resolve / reject改变状态
  • 回调先存起来(队列)
  • 若异步完成后才添加回调,仍要能触发 → 所以要用数组收集

四、then 的原理(最关键)

1. then 做了什么?

 
promise.then(onFulfilled, onRejected)
 
 
它的职责:
  • 注册成功 / 失败回调
  • 返回一个新的 Promise(实现链式调用)
  • 处理返回值(普通值 / Promise / thenable)

2. then 的简化逻辑

 
then(onFulfilled, onRejected) {
  return new Promise((resolve, reject) => {

    const handleFulfilled = () => {
      queueMicrotask(() => {
        try {
          const x = onFulfilled(this.value)
          resolve(x)
        } catch (e) {
          reject(e)
        }
      })
    }

    const handleRejected = () => {
      queueMicroTask(() => {
        try {
          const x = onRejected(this.reason)
          resolve(x)
        } catch (e) {
          reject(e)
        }
      })
    }

    if (this.state === 'fulfilled') {
      handleFulfilled()
    } else if (this.state === 'rejected') {
      handleRejected()
    } else {
      this.onFulfilledCallbacks.push(handleFulfilled)
      this.onRejectedCallbacks.push(handleRejected)
    }
  })
}
 
 
关键点:
  • then 永远返回新 Promise
  • 回调是异步执行的(微任务)
  • 返回值会决定下一个 Promise 的状态

五、为什么 Promise 是异步的(微任务)

 
Promise.resolve().then(() => console.log('then'))
console.log('sync')
 
 
输出:
 
sync
then
 
 
原因:
  • Promise 的 then/catch/finally回调
    → 被设计成 微任务(Microtask)
  • 在事件循环中:
    • 先执行同步代码
    • 再执行微任务
    • 再执行宏任务(setTimeout 等)

六、Promise 链式调用的本质

 
a.then()
 .then()
 .then()
 
 
本质是:
 
promise1 → promise2 → promise3
 
 
每一次 then
  • 返回新的 Promise
  • 上一个 Promise 的结果 → 传给下一个 onFulfilled
如果返回的是一个 Promise:
 
then(() => new Promise(...))
 
 
则:
  • 等待该 Promise 完成
  • 再决定下一个 then 的状态

七、Promise 解决“回调地狱”的原理

回调地狱:
 
async1(() => {
  async2(() => {
    async3(() => {})
  })
})
 
 
Promise 的做法:
  • 把“下一步要做什么”从嵌套变成返回值和队列
  • 用统一接口(then/catch)管理成功和失败
本质不是“更异步”,而是:
把异步控制流结构化

八、一句话总结 Promise 原理

**Promise 内部维护一个状态机和回调队列;
异步操作完成后变更状态并执行回调;
then 返回新 Promise,使链式调用和统一错误处理成为可能。**

posted on 2026-05-11 16:59  悉野  阅读(46)  评论(0)    收藏  举报