美文网首页
手写实现 Promise

手写实现 Promise

作者: 风起云帆 | 来源:发表于2019-05-08 09:19 被阅读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/ulmpoqtx.html