码迷,mamicode.com
首页 > 其他好文 > 详细

自己的Promise

时间:2019-08-19 09:52:32      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:and   ret   处理   else   实现   for   func   end   turn   

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

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);
    })
    // 如果没有处理函数,则直接抛错
    if (this.rejectCbs.length === 0) {
      throw err
    }
  }
  then(resolveCb, rejectCb) {
    if (this.status === ‘resolved‘) {
      resolveCb(this.value);
    } else if (this.status === ‘rejected‘) {
      rejectCb(this.value);
    } else {
      return new myPromise((resolve, reject) => {
        if (typeof resolveCb === ‘function‘) {
          this.resolveCbs.push(res => {
            this._handleCb(resolveCb, res, resolve, reject);
          })
        }
        if (typeof rejectCb === ‘function‘) {
          this.rejectCbs.push(res => {
            this._handleCb(rejectCb, res, resolve, reject);
          })
        }
      })
    }
  }
  catch(rejectCb) {
    return this.then(null, rejectCb)
  }
  _handleCb(cb, res, resolve, reject) {
    try {
      const ret = cb(res)
      if (ret instanceof Promise || ret instanceof myPromise) {
        ret.then(res => resolve(res))
      } else {
        resolve(ret)
      }
    } catch (err) {
      reject(err)
    }
  }
}
new myPromise((resolve, reject) => {
  setTimeout(() => {
    resolve(456)
  }, 1000);
}).then(res => {
  console.log(res)
  throw ‘hualala‘
}).catch(err => {
  console.log(‘heng!!!‘)
  return new myPromise((resolve, reject) => {
    setTimeout(() => {
      reject(233)
    }, 1000);
  })
}).then(res => {
  console.log(res)
})

这个简版的Promise已经可以实现到链式的地步了, 如果return是一个非Promise,则直接resolve,如果是Promise,则等then再resolve

自己的Promise

标签:and   ret   处理   else   实现   for   func   end   turn   

原文地址:https://www.cnblogs.com/amiezhang/p/8006370.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!