手写promise

const pending = 'pending'
const fulfilled = 'fulfilled'
const rejected = 'rejected'

class MyPromise {
  #state = pending
  #result = undefined
  #handler = []
  constructor(exector) {
    const resolve = (data) => {
      this.#changeState(fulfilled, data)
    }
    const reject = (reason) => {
      this.#changeState(rejected, reason)
    }
    try {
      exector(resolve, reject)
    } catch (err) {
      reject(err)
    }
  }
  #isPromise(prom){
     return prom!==null && (typeof prom==='object' ||typeof prom==='function') && typeof prom.then==='function'
  }
  #runOne(callback, resolve, reject) {
    if (typeof callback === 'function') {
      try {
        const ret = callback(this.#result)
        if(this.#isPromise(ret)){
          ret.then(resolve,reject)
        }else{
          resolve(ret)
        }
      } catch (err) {
        reject(err)
      }
    } else {
      const callFn = this.#state === fulfilled ? resolve : reject
      callFn(this.#result)
    }
  }
  #run() {
    if (this.#state !== pending) return;
    while (this.#handler.length) {
      const { onFulfilled, onReject, resolve, reject } = this.#handler.shift()
      if (this.#state === fulfilled) {
        this.#runOne(onFulfilled, resolve, reject)
        // if (typeof onFulfilled === 'function') {
        //   try {
        //     const ret = onFulfilled(this.#result)
        //     resolve(ret)
        //   } catch (err) {
        //     reject(err)
        //   }
        // }else{
        //   resolve(this.#result)
        // }
      } else if (this.#state === rejected) {
        this.#runOne(onReject, resolve, reject)
        // if (typeof onReject === 'function') {
        //   const err = onReject(this.#result)
        //   reject(err)
        // }else{
        //   reject(this.#result)
        // }
      }
    }
  }
  #changeState(state, data) {
    if (this.#state !== pending) return;
    this.#state = state
    this.#result = data
    this.#run()
  }
  then(onFulfilled, onReject) {
    return new MyPromise((resolve, reject) => {
      this.#handler.push({
        onFulfilled,
        onReject,
        resolve,
        reject
      })
      this.#run()
    })
  }
  toString() {
    console.log(this.#result)
  }
}

aa = new MyPromise((resolve, reject) => {
  resolve('33333')
})
aa.then(res => {
  console.log(res)
  throw new Error('eeee')
},
  err => {
    console.log(err)
  }).then(res => {
    console.log(res)
  })
// console.log(aa.toString())

 

posted @ 2024-05-22 17:47  howhy  阅读(3)  评论(0编辑  收藏  举报