从零实现一个 Promise

418 阅读8分钟

Promise 作为由社区提出和实现的异步编程解决方案,ES6 将其写进了语言标准,统一了用法,原生提供了 Promise 对象。本文将剖析 Promise 内部标准,根据 Promises/A+ 规范从零实现一个 Promise。

Promise 构造函数

在 Promise 构造函数中,主要操作是初始化状态和数据以及执行函数参数。

首先需要将状态初始化为 pending,然后定义 Promise 的值以及回调函数集。

const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'

function MyPromise(executor) {
  const self = this
  self.status = PENDING // Promise 状态,初始状态为 pending
  self.data = undefined  // Promise 的值
  self.onResolvedCallback = [] // Promise resolve 时的回调函数集
  self.onRejectedCallback = [] // Promise reject 时的回调函数集

  // 待完善,resolve 和 reject 函数
  // 待完善,执行 executor 函数
}

在构造函数中,还需要执行由外部传进来的 executor 函数,executor 函数中有两个函数参数,分别为 resolve 和 reject 函数。

function MyPromise(executor) {
  const self = this
  self.status = PENDING // Promise 状态,初始状态为 pending
  self.data = undefined  // Promise 的值
  self.onResolvedCallback = [] // Promise resolve 时的回调函数集
  self.onRejectedCallback = [] // Promise reject 时的回调函数集

  function resolve(value) {
    // 当状态为 pending 时,改变状态为 resolved,存储 Promise 值以及执行回调函数集
    if (self.status === PENDING) {
      self.status = RESOLVED
      self.data = value
      self.onResolvedCallback.map(cb => cb(value))
    }
  }

  function reject(reason) {
    // 当状态为 pending 时,改变状态为 rejected,存储 Promise 值以及执行回调函数集
    if (self.status === PENDING) {
      self.status = REJECTED
      self.data = reason
      self.onRejectedCallback.map(cb => cb(reason))
    }
  }

  try {
    executor(resolve, reject)
  } catch (e) {
    // executor 函数执行中抛出错误时该 Promise 应该被 reject
    reject(e)
  }
}

executor 函数需要使用 try catch 包裹执行的原因则是在 executor 函数执行中可能会抛出错误,当抛出错误时则该 Promise 应该被 reject,如下情况:

// 该 Promise 应该被 reject
new Promise(function(resolve, reject) {
  throw 2
})

then 方法

then 方法主要是根据 Promise 当前状态处理相应的逻辑,返回一个新的 Promise,新 Promise 的状态由原先 Promise 的状态和 then 方法函数参数中的返回值决定。

当 then 方法执行时,该 Promise 的状态是不确定的,所以需要对 Promise 的状态进行判断然后执行不同的操作,then 方法会返回一个新的 Promise。

MyPromise.prototype.then = function (onResolved, onRejected) {
  const self = this
  let promise2

  // 如果 then 的参数不是 function,则我们需要赋予默认函数实现值的透传
  onResolved = typeof onResolved === 'function' ? onResolved : value => value
  onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }

  if (self.status === RESOLVED) {
    return promise2 = new MyPromise((resolve, reject) => {
      
    })
  }

  if (self.status === REJECTED) {
    return promise2 = new MyPromise((resolve, reject) => {
      
    })
  }

  if (self.status === PENDING) {
    return promise2 = new MyPromise((resolve, reject) => {
      
    })
  }
}

then 方法会返回一个新的 Promise 后,新 Promise 的状态由原先 Promise 的状态和 then 方法函数参数中的返回值决定。

MyPromise.prototype.then = function (onResolved, onRejected) {
  const self = this
  let promise2

  // 如果 then 的参数不是 function,则我们需要赋予默认函数实现值的透传
  onResolved = typeof onResolved === 'function' ? onResolved : value => value
  onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }

  if (self.status === RESOLVED) {
    return promise2 = new MyPromise((resolve, reject) => {
      try {
        // 执行 onResolved 函数并获取返回值。若返回值是 Promise 对象,则取它的结果作为 promise2 的结果,否则以返回值作为 promise2 的结果
        const x = onResolved(self.data)
        // 按照规范,此时应调用 Promise 解决过程函数 resolutionProcedure(promise2, x, resolve, reject),这里简化了
        if (x instanceof MyPromise) {
          x.then(resolve, reject)
        }
        resolve(x)
      } catch (e) {
        // 抛出错误则以捕获到的错误作为 promise2 的结果
        reject(e)
      }
    })
  }

  if (self.status === REJECTED) {
    return promise2 = new MyPromise((resolve, reject) => {
      try {
        // 执行 onRejected 函数并获取返回值。若返回值是 Promise 对象,则取它的结果作为 promise2 的结果,否则以返回值作为 promise2 的结果
        const x = onRejected(self.data)
        // 按照规范,此时应调用 Promise 解决过程函数 resolutionProcedure(promise2, x, resolve, reject),这里简化了
        if (x instanceof MyPromise) {
          x.then(resolve, reject)
        }
        resolve(x)
      } catch (e) {
        // 抛出错误则以捕获到的错误作为 promise2 的结果
        reject(e)
      }
    })
  }

  if (self.status === PENDING) {
    return promise2 = new MyPromise((resolve, reject) => {
      // 将回调函数存进回调函数集
      self.onResolvedCallback.push((value) => {
        try {
          const x = onResolved(self.data)
          // 按照规范,此时应调用 Promise 解决过程函数 resolutionProcedure(promise2, x, resolve, reject),这里简化了
          if (x instanceof MyPromise) {
            x.then(resolve, reject)
          }
          resolve(x)
        } catch (e) {
          reject(e)
        }
      })
      self.onRejectedCallback.push((reason) => {
        try {
          const x = onRejected(self.data)
          // 按照规范,此时应调用 Promise 解决过程函数 resolutionProcedure(promise2, x, resolve, reject),这里简化了
          if (x instanceof MyPromise) {
            x.then(resolve, reject)
          } 
          resolve(x)
        } catch (e) {
          reject(e)
        }
      })
    })
  }
}

在 then 方法中根据 Promise 的当前状态分别执行了不同的操作。当状态为 resolved 时,执行 onResolved 函数(then 方法第一个函数参数)并根据返回值确定 promise2 的状态;当状态为 rejected 时,执行 onRejected 函数(then 方法第二个函数参数)并根据返回值确定 promise2 的状态;当状态为 pending 时,则需要将 onResolved 和 onRejected 函数先存进回调函数集中,等到 Promise 状态改变后再执行。

而在代码注释中说明,如果 then 的参数不是 function,则我们需要赋予默认函数实现值的透传

当传进 then 方法中 onResolved 或 onRejected 函数参数为空时,则应该赋予它们一个默认函数,该默认函数 return 或 throw 原先的参数值,这样才能正确实现 then 方法的链式调用,如下:

new MyPromise((resolve, reject) => { resolve(1) })
  .then()
  .then()
  .then((value) => {
    console.log(value)
  })

至此,我们便完成了一个符合 Promises/A+ 规范的 Promise 基础版,同原生 Promise 一样,可以通过如下方式使用:

const myPromise = new MyPromise((resolve, reject) => {
  if (/* 异步操作成功 */) {
    resolve(value);
  } else {
    reject(error);
  }
});

myPromise.then((value) => {
  console.log(value)
}, (err) => {
  console.log(err)
})

Promise 终极版

上述的代码已经能够实现一个基本 Promise 的功能,而在实际使用过程中,我们还需要根据 Promises/A+ 规范继续完善它。

需要完善的主要有以下两点:

  1. 不同 Promise 之间的兼容;
  2. 异步调用操作;

在实际中,有多种不同的 Promise 实现,关于不同 Promise 间的交互, Promises/A+ 规范已经做了详细的说明,其中详细指定了如何通过 then 的实参的返回值来决定 promise2 的状态,我们只需要按照标准将内容转成代码即可。

function resolutionProcedure(promise2, x, resolve, reject) {
  let then
  let thenCalledOrThrow = false

  if (promise2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise!'))
  }

  if (x instanceof MyPromise) { 
    if (x.status === 'pending') {
      x.then(function(value) {
        resolutionProcedure(promise2, value, resolve, reject)
      }, reject)
    } else { 
      x.then(resolve, reject)
    }
    return
  }

  if ((x !== null) && ((typeof x === 'object') || (typeof x === 'function'))) { 
    try {
      then = x.then 
      if (typeof then === 'function') {
        then.call(x, function resolvePromise(y) { 
          if (thenCalledOrThrow) return
          thenCalledOrThrow = true
          return resolutionProcedure(promise2, y, resolve, reject) 
        }, function rejectPromise(r) { 
          if (thenCalledOrThrow) return 
          thenCalledOrThrow = true
          return reject(r)
        })
      } else { 
        resolve(x)
      }
    } catch (e) { 
      if (thenCalledOrThrow) return 
      thenCalledOrThrow = true
      return reject(e)
    }
  } else { 
    resolve(x)
  }
}

所以,在 then 方法中,我们不再需要判断返回值 x 的类型,然后再根据 x 的类型去决定 promise2 的状态,只需要将其传入 resolvePromise 函数即可。

// self.status === RESOLVED 部分更改,其余两个状态更改同理
var x = onResolved(self.data)
if (x instanceof MyPromise) {
  x.then(resolve, reject)
}
resolve(x)
=>
var x = onResolved(self.data)
resolvePromise(promise2, x, resolve, reject)

最后,在标准中,说明了某些地方需要使用异步调用,在我们的实现中,我们需要在 resolve、reject、onResolved、onRejected 加上异步调用的代码,这里我们使用 setTimeout(fn, 0) 来实现。

至此,我们实现了一个符合 Promises/A+ 规范的终极版 Promise,如下:

const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'

function MyPromise(executor) {
  const self = this
  self.status = PENDING // Promise 状态,初始状态为 pending
  self.data = undefined  // Promise 的值
  self.onResolvedCallback = [] // Promise resolve 时的回调函数集
  self.onRejectedCallback = [] // Promise reject 时的回调函数集

  function resolve(value) {
    setTimeout(() => { // 异步回调
      // 当状态为 pending 时,改变状态为 resolved,存储 Promise 值以及执行回调函数集
      if (self.status === PENDING) {
        self.status = RESOLVED
        self.data = value
        self.onResolvedCallback.map(cb => cb(value))
      }
    }, 0)
  }

  function reject(reason) {
    setTimeout(() => { // 异步回调
      // 当状态为 pending 时,改变状态为 rejected,存储 Promise 值以及执行回调函数集
      if (self.status === PENDING) {
        self.status = REJECTED
        self.data = reason
        self.onRejectedCallback.map(cb => cb(reason))
      }
    }, 0)
  }

  try {
    executor(resolve, reject)
  } catch (e) {
    // executor 函数执行中抛出错误时该 Promise 应该被 reject
    reject(e)
  }
}

MyPromise.prototype.then = function (onResolved, onRejected) {
  const self = this
  let promise2

  // 如果 then 的参数不是 function,则我们需要赋予默认函数实现值的透传
  onResolved = typeof onResolved === 'function' ? onResolved : value => value
  onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }

  if (self.status === RESOLVED) {
    return promise2 = new MyPromise((resolve, reject) => {
      setTimeout(() => { // 异步回调
        try {
          // 执行 onResolved 函数并获取返回值。若返回值是 Promise 对象,则取它的结果作为 promise2 的结果,否则以返回值作为 promise2 的结果
          const x = onResolved(self.data)
          resolvePromise(promise2, x, resolve, reject)
        } catch (e) {
          // 抛出错误则以捕获到的错误作为 promise2 的结果
          reject(e)
        }
      }, 0)
    })
  }

  if (self.status === REJECTED) {
    return promise2 = new MyPromise((resolve, reject) => {
      setTimeout(() => { // 异步回调
        try {
          // 执行 onRejected 函数并获取返回值。若返回值是 Promise 对象,则取它的结果作为 promise2 的结果,否则以返回值作为 promise2 的结果
          const x = onRejected(self.data)
          resolutionProcedure(promise2, x, resolve, reject)
        } catch (e) {
          // 抛出错误则以捕获到的错误作为 promise2 的结果
          reject(e)
        }
      }, 0)
    })
  }

  if (self.status === PENDING) {
    return promise2 = new MyPromise((resolve, reject) => {
      // 将回调函数存进回调函数集
      self.onResolvedCallback.push((value) => {
        try {
          const x = onResolved(self.data)
          resolutionProcedure(promise2, x, resolve, reject)
        } catch (e) {
          reject(e)
        }
      })
      self.onRejectedCallback.push((reason) => {
        try {
          const x = onRejected(self.data)
          resolutionProcedure(promise2, x, resolve, reject)
        } catch (e) {
          reject(e)
        }
      })
    })
  }
}

function resolutionProcedure(promise2, x, resolve, reject) {
  let then
  let thenCalledOrThrow = false

  if (promise2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise!'))
  }

  if (x instanceof MyPromise) { 
    if (x.status === 'pending') {
      x.then(function(value) {
        resolutionProcedure(promise2, value, resolve, reject)
      }, reject)
    } else { 
      x.then(resolve, reject)
    }
    return
  }

  if ((x !== null) && ((typeof x === 'object') || (typeof x === 'function'))) { 
    try {
      then = x.then 
      if (typeof then === 'function') {
        then.call(x, function resolvePromise(y) { 
          if (thenCalledOrThrow) return
          thenCalledOrThrow = true
          return resolutionProcedure(promise2, y, resolve, reject) 
        }, function rejectPromise(r) { 
          if (thenCalledOrThrow) return 
          thenCalledOrThrow = true
          return reject(r)
        })
      } else { 
        resolve(x)
      }
    } catch (e) { 
      if (thenCalledOrThrow) return 
      thenCalledOrThrow = true
      return reject(e)
    }
  } else { 
    resolve(x)
  }
}

参考文章:

github.com/xieranmaya/…