手寫一個(gè)符合promise A+規(guī)范的promsie

class MyPromise {
  constructor (executor) {
    this.state = 'pending'
    this.value = this.reason = undefined
    this.onFulfilledCallback = []
    this.onRejectedCallback = []

    try {
      executor(this.resolve, this.reject)
    } catch (error) {
      this.reject(error)
    }
  }

  resolve = value => {
    if (this.state === 'pending') {
      this.state = 'fulfilled'
      this.value = value
      this.onFulfilledCallback.forEach(cb => cb())
    }
  }

  reject = reason => {
    if (this.state === 'pending') {
      this.state = 'rejected'
      this.reason = reason
      this.onRejectedCallback.forEach(cb => cb())
    }
  }

  then = (onFulfilled, onRejected) => {
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v
    onRejected = typeof onRejected === 'function' ? onRejected : r => { throw r }

    const promise2 = new MyPromise((resolve, reject) => {
      if (this.state === 'fulfilled') {
        setTimeout(() => {
          try {
            const x = onFulfilled(this.value)
            resolvePromise(promise2, x, resolve, reject);
          } catch (error) {
            reject(error)
          }
        }, 0)
      }

      if (this.state === 'rejected') {
        setTimeout(() => {
          try {
            const x = onRejected(this.reason)
            resolvePromise(promise2, x, resolve, reject);
          } catch (error) {
            reject(error)
          }
        }, 0)
      }

      if (this.state === 'pending') {
        this.onFulfilledCallback.push(() => {
          setTimeout(() => {
            try {
              const x = onFulfilled(this.value)
              resolvePromise(promise2, x, resolve, reject);
            } catch (error) {
              reject(error)
            }
          }, 0)
        })
        this.onRejectedCallback.push(() => {
          setTimeout(() => {
            try {
              const x = onRejected(this.reason)
              resolvePromise(promise2, x, resolve, reject);
            } catch (error) {
              reject(error)
            }
          })
        })
      }
    })

    return promise2
  }

  catch = fn => this.then(void 0, fn)
}

MyPromise.resolve = value => new MyPromise(resolve => resolve(value))

MyPromise.reject = reason => new MyPromise((resolve, reject) => reject(reason))

MyPromise.race = fnArr => {
  return new MyPromise((resolve, reject) => {
    fnArr.forEach(fn => {
      fn().then(resolve, reject)
    })
  })
}

MyPromise.all = fnArr => {
  const result = []
  const index = 0
  return new MyPromise((resolve, reject) => {
    fnArr.forEach((fn, i) => {
      fn().then((v) => {
        result[i] = v
        index++
        if (index === fnArr.length) {
          resolve(result)
        }
      }, reject)
    })
  })
}

function resolvePromise (promise2, x, resolve, reject) {
  if (x === promise2) {
    reject(new TypeError('Chaining cycle detected for promise'))
  }

  // 鎖
  let called

  if (x != null && (typeof x === 'object' || typeof x === 'function')) {
    try {
      const then = x.then
      if (typeof then === 'function') {
        then.call(x, y => {
          if (called) return
          called = true
          resolvePromise(promise2, y, resolve, reject)
        }, err => {
          if (called) return
          called = true
          reject(err)
        })
      } else {
        resolve(x)
      }
    } catch (error) {
      if (called) return
      called = true
      reject(error)
    }
  } else {
    resolve(x)
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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