實現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

相關文章
相關標籤/搜索