Skip to content

Promise 实现 ​

通过手写 Promise 可了解其原理、认识其特性。

一个对象或函数只要拥有 then 方法且行为满足 Promise/A+ 规范,那他就是一个 Promise。

Promise 构造函数特性 ​

在实现之前需要先列出原生 Promise 的特点。

  • 构造函数只能通过 new 来调用。
js
Promise((resolve, reject) => {})

// Uncaught TypeError: Promise constructor cannot be invoked without 'new'
  • 构造函数只接收一个参数,为执行器函数,该函数执行为同步代码。
js
Promise((resolve, reject) => {
  console.log(1)
})
console.log(2)

// 1
// 2
  • 构造函数若接收到非函数值,则抛 TypeError。
js
new Promise(null)

// Uncaught TypeError: Promise resolver null is not a function
  • 构造函数内的代码会被 try-catch 包裹,同步错误会被捕获并转为 rejected。
js
new Promise((resolve, reject) => {
  null.name
})

// Promise {<rejected>: TypeError: Cannot read properties of null (reading 'name')
// Uncaught (in promise) TypeError: Cannot read properties of null (reading 'name')
  • 构造函数内,即执行器函数内的异步错误无法被 promise 捕获,错误将冒泡到全局,所以此时用 promise 的 catch 方法无法捕获该错误。
js
const p = new Promise(() => {
  setTimeout(() => {
    null.name
  })
})

p.catch(error => {
  console.log('catch error:', error)
})

// Promise {<pending>}
// Uncaught TypeError: Cannot read properties of null (reading 'name')
  • Promise 状态一旦落定则不可变,多次调用 resolve 或 reject 时会被忽略,但该调用语句之后的代码会执行。
js
new Promise((resolve, reject) => {
  reject('no')
  resolve('ok')
  console.log('end')
})

// end
// Promise {<rejected>: 'no'}
  • 循环引用检测,resolve 的值如果是当前 promise 本身,则抛 TypeError。
js
const p = new Promise((resolve) => {
  setTimeout(() => {
    resolve(p)
  })
})

// Uncaught (in promise) TypeError: Chaining cycle detected for promise #<Promise>

Then 方法特性 ​

then 方法是核心,规范里大部分内容都是在描述 then 方法。

  • 每个 Promise 实例对象都有 then 方法,且 then 方法总是会返回一个 Promise。
js
const p = new Promise((resolve, reject) => reject())
const p2 = p.then(null, error => console.log(error))

console.log(p2)

// Promise {<fulfilled>}
  • Promise 实例执行多个 then 时,状态落定后,这些 then 方法的回调将依次执行。
js
const p = new Promise((resolve) => resolve())

p.then(() => console.log(1))
p.then(() => console.log(2))

// 1
// 2
  • then 方法的回调是异步执行,即便 promise 已经是解决状态。
js
const p = new Promise((resolve) => resolve())

p.then(() => console.log(2))
console.log(1)

// 1
// 2
  • then 的 onFulfilled 或 onRejected 方法若返回 Promise,则新 Promise 的状态由该 Promise 决定。
js
const p = new Promise(resolve => resolve())

p.then(() => {
  return Promise.reject('no')
})

// Promise {<rejected>: 'no'}
// Uncaught (in promise) no
  • 若返回的是 thenable 对象,则新 Promise 状态由该 thenable 对象里的 then 方法决定。
js
const p = new Promise(resolve => resolve())

p.then(() => {
  return {
    then(onFulfilled, onRejected) {
      onRejected('no')
    }
  }
})

// Promise {<rejected>: 'no'}
// Uncaught (in promise) no
  • 除了以上两种情况,其他返回值均会被 Promise.resolve 包裹后返回,作为兑现值。
js
const p = new Promise(resolve => resolve())

p.then(() => {
  return new Error('error')
})

// Promise {<fulfilled>: Error: error }
  • then 方法内返回 thenable 对象时,其 then 方法会被自动调用,且会接收到 onFulfilled 和 onRejected 两个回调函数,当前 promise 的状态取决于 then 内部是调用 onFulfilled 还是 onRejected,若都不调用,则状态为 pending。
js
const p = new Promise(resolve => resolve())

p.then(() => {
  return {
    then(onFulfilled, onRejected) {
      console.log('then 执行')
      console.log(onFulfilled, onRejected)
    }
  }
})

// then 执行
// ƒ () { [native code] } ƒ () { [native code] }
// Promise {<pending>}
  • then 方法的 onFulfilled 会在兑现时被调用,兑现值将作为回调参数,被拒绝时 onRejected 被调用,拒绝理由将作为参数。
js
const p = new Promise(resolve => resolve('ok'))
const p2 = new Promise((resolve, reject) => reject('no'))

p.then(res => console.log(res))
p2.then(null, error => console.log(error))

// ok
// no
  • then 方法若接收到非函数值,则会值穿透,会将前一个 promise 的值传給下一个 then。
js
const p = new Promise(resolve => resolve('ok'))

p.then()
 .then(null)
 .then(1)
 .then({ name: 'Jay'})
 .then([1, 2, 3])
 .then(res => {
   console.log(res)
 })

// ok
  • 循环引用检测,若 then 回调中返回当前 promise 本身,则抛 TypeError。
js
const p = new Promise(resolve => resolve())

const p2 = p.then(() => {
  return p2
});

// Uncaught (in promise) TypeError: Chaining cycle detected for promise #<Promise>

实现 ​

js
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise {
  #state = PENDING
  #handles = []
  #value

  constructor(executor) {
    if (!new.target) {
      throw new TypeError('Promise constructor cannot be invoked without new')
    }

    if (typeof executor !== 'function') {
      throw new TypeError(`Promise resolver ${executor} is not a function`)
    }

    const resolve = (value) => {
      this.#setState(FULFILLED, value)
    }
    const reject = (reason) => {
      this.#setState(REJECTED, reason)
    }

    // 捕获的同步错误将作为 rejected
    try {
      executor(resolve, reject)
    } catch (error) {
      reject(error)
    }
  }

  // resolve 和 reject 的调用将改变状态、保存值和执行队列中的回调
  #setState(state, value) {
    if (this.#state !== PENDING) return

    this.#state = state
    this.#value = value
    this.#runTask()
  }

  // 执行队列中所有回调并清空队列
  #runTask() {
    runMicrotask(() => {
      if (this.#state === PENDING) return

      for (let i = 0; i < this.#handles.length; i++) {
        const taskCallback = this.#handles[i]
        taskCallback()
      }
      this.#handles.length = 0
    })
  }

  then(onFulfilled, onRejected) {
    return new this.constructor((resolve, reject) => {
      this.#handles.push(() => {
        try {
          const callback = this.#state === FULFILLED ? onFulfilled : onRejected
          
          // 值穿透,若传入非函数则直接传递给下一个 then
          const result = typeof callback === 'function' ? callback(this.#value) : this.#value
          
          // promise 展开
          if (isPromiseLike(result)) {
            result.then(resolve, reject)
          } else {
            resolve(result)
          }
          
        // 执行过程中捕获到的错误将作为 rejected  
        } catch (error) {
          reject(error)
        }
      })
      this.#runTask()
    })
  }
}

// 模拟微任务
const runMicrotask = (fn) => {
  if (typeof queueMicrotask === 'function') {
    queueMicrotask(fn)
  } else if ( // Node 环境
    typeof process === 'object' &&
    typeof process.nextTick === 'function'
  ) {
    process.nextTick(fn)
  } else if (typeof MutationObserver === 'function') {
    const text = document.createTextNode('')
    const observer = new MutationObserver(fn)
    observer.observe(text, { characterData: true })
    text.data = '1'
  } else {
    setTimeout(fn)
  }
}

// 判断一个对象是否是 promise
const isPromiseLike = (obj) => {
  return obj != null && typeof obj === 'object' && typeof obj.then === 'function'
}