js手写'Promise'

2018-09-10 01:08:12来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

/*
 * pending:初始化成功
 * fulfilled:成功
 * rejected:失败
 * */

function Promise(executor) {// 执行器
    this.status = 'pending';
    this.value = undefined;
    this.reason = undefined;
    this.fulfilledCallback = [];
    this.rejectCallback = [];
    let resolve = (value)=>{
        if(this.status=='pending'){
            this.status = 'resolve';
            this.value = value;
            this.fulfilledCallback.forEach(fn=>fn())
        }
    };
    let reject = (reason)=>{
        if(this.status =='pending'){
            this.status = 'reject';
            this.reason = reason;
            this.rejectCallback.forEach(fn=>fn())
        }
    };
    try{
        executor(resolve,reject)
    }catch(e){
        reject(e)
    }
}
Promise.prototype.then = function (onfulfilled,onrejected) {
    if(this.status == 'resolve'){
        onfulfilled(this.value)
    }
    if(this.status == 'reject'){
        onrejected(this.reason)
    }
    if(this.status == 'pending'){
        this.fulfilledCallback.push(()=>{
            onfulfilled(this.value)
        });
        this.rejectCallback.push(()=>{
            onrejected(this.reason)
        })
    }
};

var a = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve(10)
    })
});
a.then((res)=>{
    console.log(res);
});

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:前端面试详解

下一篇:实用的小脚本代码汇总