封装MyPromise

封装MyPromise

Promise 有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。
(1) promise 对象初始化状态为 pending;
(2) 当调用resolve(成功),会由pending => fulfilled;
(3) 当调用reject(失败),会由pending => rejected;
注意:promise对象的状态改变,只有这两种可能,一旦状态发生改变,那么这个状态就会凝固,不会再次更改;会一直保持这个结果,这时就称为 resolved(已定型)。

//封装MyPromise
class MyPromise{
    constructor(excutor){
        // this--> 当前promise的实例;
        this.state = "pending"; //创建实例,默认状态是pending;
        this.fulfilledEvent=[]; //当前实例成功的事件池;
        this.rejectedEvent=[]; //当前实例失败的事件池;
        let resolve = (result)=>{ //只有调用resolve时,该实例的状态要改变为成功态;
            if(this.state!=="pending")return; //如果不是pending;不需要往下执行
            this.state="fulfilled";
            // 循环成功态的事件池;依次执行;
            clearTimeout(this.timer); //执行之前,首先清除之前的定时器;为了防止定时器的累加;
            this.timer = setTimeout(()=>{
                this.fulfilledEvent.forEach((item)=>{
                    if(typeof item==="function"){
                        item(result);
                    }
                })
            },0)
        }
        let reject = (result)=>{ //只有调用resolve时,该实例的状态要改变为失败态;
            if(this.state!=="pending")return;
            this.state = "rejected";
            //执行之前,首先清除之前的定时器;为了防止定时器的累加;
            clearTimeout(this.timer);
            this.timer = setTimeout(()=>{ //要用箭头函数,不用箭头函数,里面的this就丢了;
                this.fulfilledEvent.forEach((item)=>{
                    if(typeof item==="function"){
                        item(result);
                    }
                })
            },0)
        }
        try{
            // 一旦执行报错,那么会执行reject;
            //当new promise(function (resolve,reject) {}的时候,function会自动执行,所以这里要让excutor()执行;
            excutor(resolve,reject);
        }catch (e){
            reject(e);
        }
    }
    then(resolveFn,rejectFn){ //p可以调用then方法,说明then方法在promise的原型上;所以把then放到了MyPromise的原型上
        //实现then的链式写法,需要then返回一个promise的实例;
        return new MyPromise((resolve,reject)=>{
            this.fulfilledEvent.push(()=>{
                console.log(resolveFn);
                let x = resolveFn();
                // x.then : 向x的事件池中放入resolve和reject方法;
                // console.log(resolve);
                x instanceof MyPromise?x.then(resolve,reject):resolve();
            });
        })
    }
}

let p = new MyPromise(function (resolve,reject) {
   resolve(100);
});
let p1;
//then : 订阅resolve状态执行的方法;then应该向事件池中订阅方法;
p.then(function (a) { //已经捆绑到了p这个实例的事件池中;
    p1 = new MyPromise(function (resolve,reject) {
        //resolve执行会让该实例的成功的事件池执行;
        resolve();// this--> p1
    });
    return p1;
}).then(function () {
    console.log(p1.fulfilledEvent);
    console.log(1);
    //函数捆绑到上一个then返回的新的实例上;
})
/* p.then(function () {
    console.log(2);
})*/

看完上面的MyPromise代码,如果你还有些疑惑?,那看完下面这四段话,再捋一遍上面的代码就会恍然大悟了,?
第一次执行then:函数fn1被包装放到p的成功事件池中,then返回一个新的实例;
第二次执行then:函数fn2被包装放到上一个then返回的新实例的事件池中;
第一个resolve执行,执行p事件池中的fn1:fn1执行时返回一个promise实例p1,p1调用then,绑定一个第一次执行then的resolve到p1的事件池中
第二个resolve执行,执行p1事件池中的方法:resolve执行,resolve中的this指向上一级作用域的this,上一级作用域的this是第一个then执行时返回的新实例,所以让第一次执行then的实例的事件池中方法执行;

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值