「JavaScript学习笔记」 实现一个Promise

之前曾翻译过Promises/A+文档,但当时仅对文档文本内容有所了解,而实际的Promise实现仍一知半解。最近看到工业聚老师的《100 行代码实现 Promises/A+ 规范》 - 知乎,对Promise的规范有了新的理解。以下是参照前文的一个实现,主要是记录自己对Promise的理解。参考注释:

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

// 公共方法
const isObject = (obj) => !!(obj && typeof obj === 'object')
const isFunction = (fn) => typeof fn === 'function'
const isPromise = (promise) => promise instanceof Promise
const isThenable = (obj) => (isFunction(obj) || isObject(obj)) && 'then' in obj
// 1.1 一个thenable是一个函数或者对象,同时有then方法
const isIterable = (obj) => {
  if (obj == null) {
    return false
  }
  return typeof obj[Symbol.iterator] === 'function'
}


class Promise {
  constructor(f) {
    this.state = PENDING
    this.result = null
    this.callbacks = []

    const onFulfilled = (value) => transition(this, FULFILLED, value)
    const onRejected = (reason) => transition(this, REJECTED, reason)

    // 是否状态已变化 flag
    let ignore = false

    const resolve = (value) => {
      if (ignore) return
      ignore = true
      resolvePromise(this, value, onFulfilled, onRejected)
    }

    const reject = (reason) => {
      if (ignore) return
      ignore = true
      onRejected(reason)
    }
    
    // 如果执行new Promise时出错,则将错误传给reject
    try {
      f(resolve, reject)
    } catch (error) {
      reject(error)
    }
  }

  then(onFulfilled, onRejected) {
    // 2.2.7 必须返回一个Promise
    return new Promise((resolve, reject) => {
      const callback = { onFulfilled, onRejected, resolve, reject }
      // 判断注册时,当前promise的状态
      if (this.state === PENDING) {
        this.callbacks.push(callback)
      } else {
        //  如果不是pending,则异步执行掉它  3.1 
        setTimeout(() => handleCallback(callback, this.state, this.result), 0)
        // handleCallback拿到的resolve,reject都是属于then方法返回的promise,我们将它记为promise2
      }
    })
  }

  // 规范内没有的, ES6的部分实现
  catch(onRejected) {
    return this.then(null, onRejected)
  }
  static resolve(value) {
    return new Promise((resolve) => resolve(value))
  }
  static reject(reason) {
    return new Promise((_, reject) => reject(reason))
  }
  
  static all(promises) {
    if (!isIterable(promises)) {
      throw new TypeError('params is not iterable')
    }
    const results = []
    let count = 0
    let done = false

    return new Promise((resolve, reject) => {
      for (const p of promises) {
        const i = count++ // 同步遍历所有迭代器内容
        Promise.resolve(p).then(
          (result) => {
            if (done) return
            results[i] = result
            count-- // resolve 就减少一个count
            if (count === 0 ) {
              resolve(results)
            }
          },
          (error) => {
            if (done) return
            done = true
            reject(error)
          }
        )
      }
      // 如果传入的迭代器成员为空,则直接返回迭代器本身
      if (count === 0) { resolve(promises) }
    })
  }

  static race(promises) {
    if (!isIterable(promises)) {
      throw new TypeError('params is not iterable')
    }

    let done = false

    return new Promise((resolve, reject) => {
      for (const p of promises) {
        count++
        Promise.resolve(p).then((result) => {
          if (done) return
          done = true
          resolve(result)
        }, (error) => {
          if (done) return
          done = true
          reject(error)
        })
      }
    })
  }
}

// promise状态迁移公共方法
const transition = (promise, state, result) => {
  if (promise.state !== PENDING) return
  promise.state = state
  promise.result = result
  // 异步将所有callbacks执行掉
  setTimeout(() => {
    // resolve时,处理掉所有注册的任务
    while (callbacks.length) handleCallback(callbacks.shift(), state, result)
  }), 0)
}

// 执行then方法注册onFulfilled或处理错误
const handleCallback = (callback, state, result) => {
  const { onFulfilled, onRejected, resolve, reject } = callback // resolve, reject 是 then返回的Promise注册的方法
  try {
    // isFunction: 2.2.1 不是函数则忽略
    if (state === FULFILLED) {
      // 2.2.7
      isFunction(onFulfilled) ? resolve(onFulfilled(result)) : resolve(result)
    } else if (state === REJECTED) {
      isFunction(onRejected) ? resolve(onRejected(result)) : reject(result)
    }
  } catch (error) {
    reject(error)
  }
}

// 2.3 Promise Resolution Procedure 提供互通性
// onFulfilled的返回值 x 如果也是一个符合规范的 promise对象(thenable),
const resolvePromise = (promise, x, resolve, reject) => {
  // 2.3.1
  if (x === promise) {
    const reason = new TypeError('Can not fufill promise with itself')
    return reject(reason)
  }

  // 2.3.2 
  // 当resolve一个x时,需要等待x的状态结束,再resolve promise自身
  // 即,检查resolve的value 是否是promise,如果是,则通过then方法注册,将 promise的状态迁移注册给 x 的then方法,等待x的fulfilled
  if (isPromise(x)) {
    return x.then(resolve, reject)
  }
  // 检查x是否为thenable对象,如果是,则表示它可以尝试让当前实现的Promise处理
  // 通过这种方式接受其他符合A+规范的的Promise实现(实现了then方法的Promise)
  if (isThenable(x)) {
    try {
      const then = x.then
      if (isFunction(then)) {
        // 当x有then方法,表示它是一个兼容的Promise实现
        // 这里创建一个新的Promise,将x的then传入,并且then原来的resolve
        // 执行另一个异步流程,也就是说等待x的状态最终为fufilled/rejected执行原来的resolve/reject
        // 实现了对其他Promise实现的兼容
        return new Promise(then.bind(x)).then(resolve, reject)
      }
    } catch (error) {
      return reject(error)
    }
  }
  
  // 如果都不是,则resolve掉这个值
  resolve(x)
}

除了基本实现,工业聚老师的文章还提到一些关于callback style async的内容,十分受用,这里就不展开来说,原文非常精彩,建议去看一下。

你可能感兴趣的:(「JavaScript学习笔记」 实现一个Promise)