自己的Promise

允我心安 提交于 2019-11-27 20:29:39

废话不多说,直接上代码:

class myPromise {
  constructor(fn) {
    this.status = 'pending';
    this.resolveCbs = [];
    this.rejectCbs = [];
    this.value = null;
    fn(this.resolve.bind(this), this.reject.bind(this))
  }
  resolve(val) {
    this.value = val;
    this.status = 'resolved';
    this.resolveCbs.forEach(cb => {
      cb(this.value);
    })
  }
  reject(err) {
    this.value = err;
    this.status = 'rejected';
    this.rejectCbs.forEach(cb => {
      cb(this.value);
    })
  }
  then(resolveCb, rejectCb) {
    if (this.status === 'resolved') {
      resolveCb(this.value);
    } else if (this.status === 'rejected') {
      rejectCb(this.value);
    } else {
      if (typeof resolveCb === 'function') {
        this.resolveCbs.push(resolveCb)
      }
      if (typeof resolveCb === 'function') {
        this.rejectCbs.push(resolveCb)
      }
    }
  }
}
new myPromise((resolve, reject) => {
  setTimeout(() => {
    resolve(456)
  }, 1000);
}).then(res => {
  console.log(res)
})

这个简版的Promise只能实现一层then,不能做链式。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!