简单版promise实现方法

211 阅读1分钟
class MyPromise {
  constructor(fn) {
    //promise接受一个函数
    this.successList = []
    this.failList = []
    this.state = "pending" //fullfilled rejected
    this.value = null
    fn(this.resolveFn.bind(this), this.rejectFn.bind(this))
  }
  then(successFn, failFn) {
    if (typeof successFn === 'function') {
      this.successList.push(successFn)
    }
    if (typeof failFn === 'function') {
      this.failList.push(successFn)
    }

  }
  catch (failFn) {
    this.then(null, failFn)
  }
  resolveFn(res) {
    this.state = 'fullfilled'
    for (let i = 0; i < this.successList.length; i++) {
      let fn = this.successList[i]
      fn(res)
    }
  }
  rejectFn(res) {
    this.state = 'rejected'
    for (let i = 0; i < this.failList.length; i++) {
      let fn = this.failList[i]
      fn(res)
    }
  }
}
let mypromise = new MyPromise((resolve,reject)=>{
  setTimeout(()=>{
    resolve(123456)
  },2000)
})
mypromise.then(function(res){console.log(res)},function(){})