学习promise

 function MPromise(fn) {
  this.value  // 给一个默认值
  this.status = "pending" // 初始pending状态变到resolved或者rejected状态
  this.resolveFunction = function () {} 
  this.rejectFunction = function () {}
  fn(this.resolve.bind(this), this.reject.bind(this))
}
MPromise.prototype.resolve = function (val) {
  var self = this
  if (this.status === "pending") {
    this.status = "resolved" // 改变status 避免promise同时走reslove以及reject流程
    self.value = val
    setTimeout(function () {
      self.resolveFunction(self.value)
    }, 0)
  }
}
MPromise.prototype.reject = function (val) {
  var self = this
  if (this.status === "pending") {
    this.status = "rejected"  // 改变status 避免promise同时走reslove以及reject流程
    self.value = val
    /**
    * 为什么要用setTimeout(()=>{},0) ?
    * 首先从函数执行顺序来讲
    * 1. new MPromise(function(resolve,reject){}) --> 调用的是 function MPromise (){} --> 初始化resolveFunction 、rejectFunction函数
    * 2.在function MPromise (){} 中调用了回调方法 fn ,触发了MPromise.prototype.resolve 、 MPromise.prototype.reject
    * 3.如果不用setTimeout ,MPromise.prototype.resolve 的基础写法为 MPromise.prototype.resolve = 
    * function (val){
    *  this.value = val
    *  this.resolveFunction(self.value)
    *}
    * 4. fn函数就已经在执行了,然而,p.then这个方法是在后面才定义了resolve和reject 
    * 5. 所以需要setTimeout去利用js的单线程+消息队列,在主线程代码执行完毕才能开始执行消息队列当中的代码
    * 6.这样就可以在.then中去定义了resolve和reject 
    */
    setTimeout(function () {
      self.rejectFunction(self.value)
    }, 0)
  }
}
MPromise.prototype.then = function (resolveFunction, rejectFunction) {
  var self = this
  return new MPromise(function (resolve_next, reject_next) {
    function resolveWarp() {
       // var result = resolveFunction(self.value) 这一句的理解
      // 一开始想不明白为啥要这句,不可以直接 resolve_next(result) 吗
      // var result = resolveFunction(self.value) 其实就是 resolveFunction 是否设置了返回值,未设置则为undefined
      // 如果不执行这一句,则p.then(res=>{ // res永远都是undefined }) 因为没有返回值
      var result = resolveFunction(self.value)
      if(result && typeof result.then === 'function'){
        result.then(resolve_next, reject_next)
      }else {
        resolve_next(result)
      }
    }
    function rejectWarp() {
      var result = rejectFunction ? rejectFunction(self.value) : function(){}
      if (result && typeof result.then === 'function') {
        //如果result是MPromise对象,则通过then将resolve_next和reject_next传给它
        result.then(resolve_next, reject_next);
      } else {
        //如果result是其他对象,则作为参数传给resolve_next
        resolve_next(result);
      }
    }
    self.resolveFunction = resolveWarp
    self.rejectFunction = rejectWarp
  })
}
var p = new MPromise((resolve, reject) => {
  resolve("less than 0.5")
  // reject("more than 0.5")
})
p.then((res) => {
  console.log(res)
  // return res
})

参考地址:https://www.cnblogs.com/malin...

评论

暂无评论