美文网首页
实现一个简单的Promise

实现一个简单的Promise

作者: 诺CIUM | 来源:发表于2019-03-27 22:33 被阅读0次
    function Promise(executor) {
        let self = this;
        self.status = 'pending'; //等待态
        self.value = undefined;  //成功的返回值
        self.reason = undefined; //失败的原因
    
        function resolve(value){
            if(self.status === 'pending'){
                self.status = 'resolved';
                self.value = value;
            }
        }
        function reject(reason) {
            if(self.status === 'pending') {
                self.status = 'rejected';
                self.reason = reason;
            }
        }
        try{
            executor(resolve, reject);
        }catch(e){
            reject(e);// 捕获时发生异常,就直接失败
        }
    }
    //onFufiled 成功的回调
    //onRejected 失败的回调
    Promise.prototype.then = function (onFufiled, onRejected) {
        let self = this;
        if(self.status === 'resolved'){
            onFufiled(self.value);
        }
        if(self.status === 'rejected'){
            onRejected(self.reason);
        }
    }
    module.exports = Promise;
    

    相关文章

      网友评论

          本文标题:实现一个简单的Promise

          本文链接:https://www.haomeiwen.com/subject/koexbqtx.html