码迷,mamicode.com
首页 > Web开发 > 详细

js手写'Promise'

时间:2018-09-09 21:04:39      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:The   res   span   class   fill   promise   手写   time   tag   

/*
 * 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);
});

 

js手写'Promise'

标签:The   res   span   class   fill   promise   手写   time   tag   

原文地址:https://www.cnblogs.com/wumi/p/9614962.html

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