Promise实现

123 阅读1分钟

Promise的调用流程:

  • Promise的构造方法接收一个回调函数executor(),在new Promise()时就立刻执行这个回调函数executor()。
  • 回调函数内部的异步任务被放入宏/微任务队列,等待执行
  • then()被执行,收集成功/失败回调,放入成功/失败队列
  • 回调函数executor()的异步任务被执行,触发resolve/rejuce,从成功/失败队列中取出回调依次执行

Promise规范

  • Promise本质是一个状态机,且状态只能为以下三种:Pending(等待态)、Fulfilled(执行态)、Rejected(拒绝态),状态的变更是单向的,只能从Pending -> Fulfilled 或 Pending -> Rejected,状态变更不可逆。
  • then方法接收两个可选参数,分别对应状态改变时触发的回调。then方法返回一个promise。then 方法可以被同一个 promise 调用多次。
const PENDING = 'pending'
cosnt FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
    constructor(executor) {
        this._status = PENDING // Promise状态
        this._resolveQueue = [] // then收集的执行成功的回调队列
        this._rejectQueue = [] // then收集的执行失败的回调队列
        // 由于resolve/reject是在executor内部被调用,因此需要使用箭头函数固定this指向,否则找不到this._resolveQueue
        let _resolve = (val) => {
            if (this._status !== PENDING) return // 对应规范中的“状态只能有pending到fulfilled或rejected”
            this._status = FULFILLED // 变更状态
            // 从成功队列里取出回调依次执行
            while(this._resolveQueue.length) {
                const callback = this._resolveQueue.shift()
                callback(val)
            }
        }
        let _reject = (val) => {
            if (this._status !== PENDING) return // 对应规范中的“状态只能有pending到fulfilled或rejected”
            this._status = REJECTED // 变更状态
            while(this._rejectQueue.length) {
                const callback = this._rejectQueue.shift()
                callback(val)
            }
        }
        // new Promise()时立即执行executor,并传入resolve和reject
        executor(_resolve, _reject)
    }
    then(resolveFn, rejectFn) {
        this._resolveQueue.push(resolveFn)
        this._rejectQueue.push(rejectFn)
    }
}