欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

实现一个简陋地Promise

程序员文章站 2022-07-03 09:32:26
...

简单实现地代码如下

class PromiseTest{
  constructor(callBack){
    this.successEventBus = [];
    this.value = null;
    this.failedEventBus = [];
    const reslove = (successData) => {
      this.value = successData;
      this.successEventBus.forEach( cb => cb(this.value))
    }
    const reject = (failedData) => {
      this.value = failedData;
      this.failedEventBus.forEach( cb => cb(this.value))
    }
    callBack(reslove, reject)  
  }
  then(cb){
    this.successEventBus.push(cb)
  }
  catch(cb){
    this.failedEventBus.push(cb)
  }

}

使用如下

let cc = new PromiseTest((reslove, reject) => {
  setTimeout(()=>{
    reslove(1)
  },10000)

})
cc.then(res => {
  console.log(res, '+++')
})
相关标签: promise