Shanyue. tech/code/Promis…

implementation

A crude implementation of a simple Promise, the key here

  1. whenpendingWhen,thenableFunctions are maintained by a queue
  2. When the state becomesresolved(fulfilled)When, all of thethenableFunction performs
  3. whenresolvedWhen,thenableFunction direct execution

The same with rejected state

class Prom {
  static resolve (value) {
    if (value && value.then) {
      return value 
    }
    return new Prom(resolve= > resolve(value))
  }

  constructor (fn) {
    this.value = undefined
    this.reason = undefined
    this.status = 'PENDING'

    // Maintain a resolve/pending function queue
    this.resolveFns = []
    this.rejectFns = []

    const resolve = (value) = > {
      // Notice the setTimeout here
      setTimeout((a)= > {
        this.status = 'RESOLVED'
        this.value = value
        this.resolveFns.forEach(({ fn, resolve: res, reject: rej }) = > res(fn(value)))
      })
    }

    const reject = (e) = > {
      setTimeout((a)= > {
        this.status = 'REJECTED'
        this.reason = e
        this.rejectFns.forEach(({ fn, resolve: res, reject: rej }) = > rej(fn(e)))
      })
    }

    fn(resolve, reject)
  }


  then (fn) {
    if (this.status === 'RESOLVED') {
      const result = fn(this.value)
      // Return a Promise
      // If resolved, execute
      return Prom.resolve(result)
    }
    if (this.status === 'PENDING') {
      // Return a Promise
      return new Prom((resolve, reject) = > {
        // In the queue, resolved
        this.resolveFns.push({ fn, resolve, reject }) 
      })
    }
  }

  catch (fn) {
    if (this.status === 'REJECTED') {
      const result = fn(this.value)
      return Prom.resolve(result)
    }
    if (this.status === 'PENDING') {
      return new Prom((resolve, reject) = > {
        this.rejectFns.push({ fn, resolve, reject }) 
      })
    }
  }
}

Prom.resolve(10).then(o= > o * 10).then(o= > o + 10).then(o= > {
  console.log(o)
})

return new Prom((resolve, reject) = > reject('Error')).catch(e= > {
  console.log('Error', e)
})
Copy the code

Welcome to pay attention to my public number shanyuexixing, here records my technical growth, welcome to exchange