Promise實現(xiàn)

 var executeAsync
  if (typeof process=='object' && process.nextTick) {
    executeAsync = process.nextTick
  } else if (typeof setImmediate=='function') {
    executeAsync = setImmediate
  } else {
    executeAsync = function (fn) {setTimeout(fn, 0)}
  }
  function callAsync(fn, arg, callback, onError) {
    executeAsync(function () {
      try {
        callback ? callback(fn(arg)) : fn(arg)
      } catch (e) {
        onError(e)
      }
    })
  }

  // 判斷變量否為function
  const isFunction = variable => typeof variable === 'function'
  // 定義Promise的三種狀態(tài)常量
  const PENDING = 'pending'
  const FULFILLED = 'fulfilled'
  const REJECTED = 'rejected'

  class MyPromise {
    constructor(handle) {
      if (!isFunction(handle)) {
        throw new Error('MyPromise must accept a function as a parameter')
      }
      // 添加狀態(tài)
      this._status = PENDING
      // 添加狀態(tài)
      this._value = null
      // 添加成功回調(diào)函數(shù)隊列
      this._fulfilledQueue = []
      // 添加失敗回調(diào)函數(shù)隊列
      this._rejectedQueue = []
      // 執(zhí)行handle
      try {
        handle(this._resolve.bind(this), this._reject.bind(this)) 
      } catch (err) {
        this._reject(err)
      }
    }
    // 添加resovle時執(zhí)行的函數(shù)
    _resolve(val) {
      if (this._status !== PENDING) return
      this._status = FULFILLED
      // 依次執(zhí)行成功隊列中的函數(shù),并清空隊列
      const runFulfilled = (value) => {
        let cb;
        while (cb = this._fulfilledQueue.shift()) {
          cb(value)
        }
      }
      // 依次執(zhí)行失敗隊列中的函數(shù),并清空隊列
      const runRejected = (error) => {
        let cb
        while (cb = this._rejectedQueue.shift()) {
          cb(error)
        }
      }
      /* 如果resolve的參數(shù)為Promise對象,則必須等待該Promise對象狀態(tài)改變后,
        當前Promsie的狀態(tài)才會改變,且狀態(tài)取決于參數(shù)Promsie對象的狀態(tài)
      */
      if (val instanceof MyPromise) {
        val.then(value => {
          this._value = value
          runFulfilled(value)
        }, err => {
          this._value = err
          runRejected(err)
        })
      } else {
        this._value = val
        runFulfilled(val)
      }
    }
    // 添加reject時執(zhí)行的函數(shù)
    _reject(err) { 
      if (this._status !== PENDING) return
      // 依次執(zhí)行失敗隊列中的函數(shù),并清空隊列
      this._status = REJECTED
      this._value = err
      let cb
      while (cb = this._rejectedQueue.shift()) {
        cb(err)
      }
    }
    // 添加then方法
    then(onFulfilled, onRejected) {
      // 返回一個新的Promise對象
      return new MyPromise((onFulfilledNext, onRejectedNext) => {
        // 封裝一個成功時執(zhí)行的函數(shù)
        let fulfilled = value => {
          if (isFunction(onFulfilled)) {
            callAsync(onFulfilled, value, res => {
              if (res instanceof MyPromise) {
                // 如果當前回調(diào)函數(shù)返回MyPromise對象,必須等待其狀態(tài)改變后在執(zhí)行下一個回調(diào)
                res.then(onFulfilledNext, onRejectedNext)
              } else {
                // 否則會將返回結(jié)果直接作為參數(shù),傳入下一個then的回調(diào)函數(shù),并立即執(zhí)行下一個then的回調(diào)函數(shù)
                onFulfilledNext(res)
              }
            }, onRejectedNext)
          } else {
            try {
              onFulfilledNext(value)
            } catch (err) {
              // 如果函數(shù)執(zhí)行出錯,新的Promise對象的狀態(tài)為失敗
              onRejectedNext(err)
            }
          }
        }
        // 封裝一個失敗時執(zhí)行的函數(shù)
        let rejected = error => {
          if (isFunction(onRejected)) {
            callAsync(onRejected, error, res => {
              if (res instanceof MyPromise) {
                // 如果當前回調(diào)函數(shù)返回MyPromise對象,必須等待其狀態(tài)改變后在執(zhí)行下一個回調(diào)
                res.then(onFulfilledNext, onRejectedNext)
              } else {
                // 否則會將返回結(jié)果直接作為參數(shù),傳入下一個then的回調(diào)函數(shù),并立即執(zhí)行下一個then的回調(diào)函數(shù)
                onFulfilledNext(res)
              }
            }, onRejectedNext)
          } else {
            try {
              onRejectedNext(error)
            } catch (err) {
              // 如果函數(shù)執(zhí)行出錯,新的Promise對象的狀態(tài)為失敗
              onRejectedNext(err)
            }
          }
        }

        switch (this._status) {
          // 當狀態(tài)為pending時,將then方法回調(diào)函數(shù)加入執(zhí)行隊列等待執(zhí)行
          case PENDING:
            this._fulfilledQueue.push(fulfilled)
            this._rejectedQueue.push(rejected)
            break
          // 當狀態(tài)已經(jīng)改變時,立即執(zhí)行對應(yīng)的回調(diào)函數(shù)
          case FULFILLED:
            fulfilled(this._value)
            break
          case REJECTED:
            rejected(this._value)
            break
        }
      })
    }
    // 添加catch方法
    catch(onRejected) {
      return this.then(null, onRejected)
    }
    // 添加靜態(tài)resolve方法
    static resolve(value) {
      // 如果參數(shù)是MyPromise實例或thenable對象,直接返回value
      return value instanceof MyPromise ||
        (value && isFunction(value.then)) ? value :
        new MyPromise(resolve => resolve(value))
    }
    // 添加靜態(tài)reject方法
    static reject(value) {
      return new MyPromise((resolve, reject) => reject(value))
    }
    // 添加靜態(tài)all方法
    static all(list) {
      return new MyPromise((resolve, reject) => {
        let values = [], count = list.length
        for (let i in list) {
          // 數(shù)組參數(shù)如果不是MyPromise實例,先調(diào)用MyPromise.resolve
          this.resolve(list[i]).then(res => {
            values[i] = res
            // 所有狀態(tài)都變成fulfilled時返回的MyPromise狀態(tài)就變成fulfilled
            --count<1 && resolve(values)
          }, reject)
        }
      })
    }
    // 添加靜態(tài)race方法
    static race(list) {
      return new MyPromise((resolve, reject) => {
        for (let p of list) {
          // 只要有一個實例率先改變狀態(tài),新的MyPromise的狀態(tài)就跟著改變
          this.resolve(p).then(res => {
            resolve(res)
          }, reject)
        }
      })
    }
    finally(cb) {
      return this.then(
        value  => MyPromise.resolve(cb()).then(() => value),
        reason => MyPromise.resolve(cb()).then(() => { throw reason })
      )
    }
  }

  // 測試代碼
  new MyPromise(resolve => {
    console.log(1);
    resolve(3);
    MyPromise.resolve().then(() => console.log(4)).then(() => console.log(5))
  }).then(num => { console.log(num) }).then(() => { console.log(6) });
  console.log(2)
  // 依次輸出:1 2 4 3 5 6
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容