实现Promise基本原理

let P = class {数组

constructor(callback) {
    this.resolveSet = [];
    this.rejectSet = [];
    setTimeout(() => { **// 先把then的回调先push到数组 ,而后在调用该回调**
      callback(this.resolve.bind(this), this.reject.bind(this))
    }, 0);
  }

  resolve(result) {
    this.resolveSet.reduce((before, current,i) => { //  链式调用
      if(i ===1){
        return current(before(result))
      }else{
        return current(before)
      }
    })
  }
  
  reject(err) {}

  then(callback) {
    this.resolveSet.push(callback);
    return this
  }
  catch (callback) {}
}
new P((resolve, reject) => {
  return resolve({
    result: 'resolve'
  })
}).then(data => {
  return {
    result: 1
  }
}).then((x) => {
  return {result:2}
}).then(x=>{
  debugger
}),

一个简单是实现原理,resolve方法中使用reduce,为的是链式调用,首次遍历callback数组时,下标为 1,传入到首次的返回结果。
若是有错请各位多多指点,勿喷,this

相关文章
相关标签/搜索