最简单的Promise方法实现

class PromiseA {
  constructor(process) {
    this.status = pending; // 实例化状态
    this.msg = ''; // 成功后返回的数据
    process(this.resolve.bind(this), this.reject.bind(this))
    return this;
  },
  resolve(val) { // 成功回调
    this.status = 'fulfilled';
    this.msg = val;
  },
  reject(err) { // 失败回调
    this.status = 'reject';
    this.msg = err;
  },
  then(fulfilled, reject) {
    if(this.status === 'fulfilled') {
      fulfilled(this.msg)
    } else if(this.status === 'reject') {
      reject(this.msg)
    }
  }
}

测试代码

const test = new PromiseA(function(resolve,reject) {
  resolve('测试代码')
})
test.then(function(success) {
  console.log(success)
}, function(err) => {
  console.log('fail')
})
posted on 2022-05-30 10:34  打怪升级小妮子  阅读(12)  评论(0)    收藏  举报