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

自己的Promise

时间:2017-12-08 18:22:10      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:his   promise   stat   style   使用   function   ret   ext   bsp   

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

class Promise2{
  constructor(fn){
    const _this=this;
    //重点
    this.__queue=[];

    this.__succ_res=null;
    this.__erro_res=null;

    this.status=‘‘;

    fn(function (...arg){
      _this.__succ_res=arg;

      _this.status=‘succ‘;

      _this.__queue.forEach(json=>{
        json.fn1(...arg);
      });
    }, function (...arg){
      _this.__erro_res=arg;

      _this.status=‘error‘;

      _this.__queue.forEach(json=>{
        json.fn2(...arg);
      });
    });
  }

  then(fn1, fn2){
    if(this.status==‘succ‘){
      fn1(...this.__succ_res);
    }else if(this.status==‘error‘){
      fn2(...this.__erro_res);
    }else{
      this.__queue.push({fn1, fn2});
    }
  }
}

Promise2.all=function (arr){
  let arr=[];

  return Promise2(function (resolve, reject){
    let i=0;

    function next(){
      arr[i].then(function (res){
        arr.push(res);

        i++;
        if(i==arr.length){
          resolve(arr);
        }else{
          next();
        }
      }, reject);
    }
  });
};

可以说,这个自己重构的promise比官方的promise都要好,因为官方的promise居然,居然没有then的情况下,传给promise的函数还是调用了resolve和reject  (lll¬ω¬)

而这个自己写的promise,考虑好2种情况:

1.正常的异步,调用resolve和reject慢于then的使用:我们会先把then方法存进数组里面,待resolve和reject被调用

2.乱写的同步(有些大脑回路不正常的人居然用promise写同步),调用resolve和reject先于then的使用,我们会先把成功或者失败的状态和参数存好,然后待then调用的时候,再调用then传入的两个函数

自己的Promise

标签:his   promise   stat   style   使用   function   ret   ext   bsp   

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

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