手把手教你实现一个完整的 Promise es6学习笔记5--promise大白话讲解Promise(一)

前端开发 作者: 2024-08-25 23:05:01
用过 Promise,但是总是有点似懂非懂的感觉,也看过很多文章,还是搞不懂 Promise的 实现原理,后面自己边看文章,边调试代码,终于慢慢的有感觉了,下面就按自己的理解来实现一个 Promise
function fn1(resolve,reject) {
    setTimeout(() {
        console.log('步骤一:执行');
        resolve('1');
    },500);
}

 fn2(resolve,1)">() {
        console.log('步骤二:执行');
        resolve('2'new Promise(fn1).then((val){
    console.log(val);
    return new Promise(fn2);
}).then(return 33;
}).then((val){
    console.log(val);
});
 Promise(fn){
  //需要一个成功时的回调
  var callback;
  一个实例的方法,用来注册异步事件
  this.then = (done){
    callback = done;
  }
   resolve(){
    callback();
  }
  fn(resolve);
}
 Promise(fn) {
    var promise = this,value = null;
        promise._resolves = [];

     (onFulfilled) {
        promise._resolves.push(onFulfilled);
        ;
    };

     resolve(value) {
        promise._resolves.forEach( (callback) {
            callback(value);
        });
    }

    fn(resolve);
}
  • then方法中的 return this 实现了链式调用。
     resolve(value) {
        setTimeout(() {
            promise._resolves.forEach( (callback) {
                callback(value);
            });
        },0);
    }
 [];
        promise._status = 'PENDING';

     (onFulfilled) {
        if (promise._status === 'PENDING') {
            promise._resolves.push(onFulfilled);
            ;
        }
        onFulfilled(value);
        return this;
    };


     resolve(value) {
        setTimeout((){
            promise._status = "FULFILLED";
            promise._resolves.forEach( (callback) {
                callback(value);
            })
        },0);
    }

    fn(resolve);
}
     resolve(value) {
        setTimeout((){
            promise._status = "FULFILLED";
            promise._resolves.forEach( (callback) {
                value = callback(value);
            })
        },1)">);
    }
     (onFulfilled) {
        new Promise((resolve) {
            function handle(value) {
                var ret = isFunction(onFulfilled) && onFulfilled(value) || value;
                resolve(ret);
            }
            if (promise._status === 'PENDING') {
                promise._resolves.push(handle);
            } else if(promise._status === FULFILLED){
                handle(value);
            }
        })
        
    };
fn1).then(fn2).then(fn3)})
(resolve) {
             handle(value) {
                var ret = typeof onFulfilled === 'function' && onFulfilled(value) || value;
                if( ret && typeof ret ['then'] == 'function'){
                    ret.then(function(value){
                       resolve(value);
                    });
                } else {
                    resolve(ret);
                }
            }
             FULFILLED){
                handle(value);
            }
        })
        
    };
     (onFulfilled(resolve.......
            }
            function errback(reason){
                reason = isFunction(onRejected) && onRejected(reason) || reason;
                reject(reason);
            }
            ) {
                promise._resolves.push(handle);
                promise._rejects.push(errback);
            } if(promise._status === 'FULFILLED'){
                handle(value);
            } else if(promise._status === 'REJECTED') {
              errback(promise._reason);
        }
        })
        
    };

    function reject(value) {
        setTimeout(function(){
            promise._status = "REJECTED";
            promise._rejects.forEach(function (callback) {
                promise._reason = callback( value);
            })
        },0);
    }
Promise.all = (promises){
    if (!Array.isArray(promises)) {
        throw new TypeError('You must pass an array to all.');
      }
    // 返回一个promise 实例
(resolve,reject){ var i = 0 [],len = promises.length,  count = len;
      // 每一个 promise 执行成功后,就会调用一次 resolve 函数
resolver(index) {   (value) {    resolveAll(index,value);   };  } rejecter(reason){ reject(reason); } resolveAll(index,value){
       存储每一个promise的参数
result[index] = value;
       等于0 表明所有的promise 都已经运行完成,执行resolve函数
if( --count == 0){ resolve(result) } }       依次循环执行每个promise for (; i < len; i++) {
         // 若有一个失败,就执行rejecter函数
promises[i].then(resolver(i),rejecter); } }); }
Promise.race = Array.isArray(promises)) {
        new TypeError('You must pass an array to race.');
    }
    return Promise( promises.length;

         resolver(value) {
            resolve(value);
        }

        ) {
            promises[i].then(resolver,rejecter);
        }
    });
}
((window,undefined){

 resolve 和 reject 最终都会调用该函数
var final = (status,value){
    if(promise._status !== 'PENDING') ;
    
     所以的执行都是异步调用,保证then是先执行的
    setTimeout((){
        promise._status = status;
        st = promise._status === 'FULFILLED'
        queue = promise[st ? '_resolves' : '_rejects'];

        while(fn = queue.shift()) {
            value = fn.call(promise,value) || value;
        }

        promise[st ? '_value' : '_reason'] = value;
        promise['_resolves'] = promise['_rejects'] = undefined;
    });
}


参数是一个函数,内部提供两个函数作为该函数的参数,分别是resolve 和 reject
var Promise = (resolver){
    if (!(typeof resolver === 'function' ))
        new TypeError('You must pass a resolver function as the first argument to the promise constructor');
    如果不是promise实例,就new一个
    if(!(this instanceof Promise))  Promise(resolver);

    ;
    promise._value;
    promise._reason;
    promise._status = 'PENDING';
    存储状态
    promise._resolves = [];
    promise._rejects = [];
    
    //
    var resolve = (value) {
        由於apply參數是數組
        final.apply(promise,['FULFILLED'].concat([value]));
    }

    var reject = (reason){
        final.apply(promise,['REJECTED'].concat([reason]));
    }
    
    resolver(resolve,reject);
}

Promise.prototype.then = (onFulfilled,onRejected){
     每次返回一个promise,保证是可thenable的
     handle(value) {
             這一步很關鍵,只有這樣才可以將值傳遞給下一個resolve
             value;

            判断是不是promise 对象
            if (ret && typeof ret ['then'] == 'function') {
                ret.then((value) {
                    resolve(value);
                },(reason) {
                    reject(reason);
                });
            } else {
                resolve(ret);
            }
        }

         errback(reason){
            reason = typeof onRejected === 'function' && onRejected(reason) || reason;
            reject(reason);
        }

        if(promise._status === 'PENDING'){
            promise._resolves.push(handle);
            promise._rejects.push(errback);
        }if(promise._status === FULFILLED){  状态改变后的then操作,立刻执行
            callback(promise._value);
        } REJECTED){
            errback(promise._reason);
        }
    });
}

Promise.prototype.catch = (onRejected){
    .then(undefined,onRejected)
}

Promise.prototype.delay = (ms,1)">this.then((ori){
        return Promise.delay(ms,value || ori);
    })
}

Promise.delay = (){
            resolve(value);
            console.log('1');
        },ms);
    })
}

Promise.resolve = (arg){
    =  len
            
        这里与race中的函数相比,多了一层嵌套,要传入index
         resolver(index) {
          (value) {
            resolveAll(index,value);
          };
        }

         value;
            ){
                resolve(result)
            }
        }

        ) {
            promises[i].then(resolver(i),rejecter);
        }
    });
}

Promise.race =  Promise;

})(window);
View Code
var getData100 = (){
    (){
            resolve('100ms');
    });
}

var getData200 = (){
            resolve('200ms');
    });
}
var getData300 = (){
            reject('reject');
    });
}

getData100().then((data){
    console.log(data);       100ms
     getData200();
}).then( 200ms
     getData300();
}).then((data){
    console.log(data);      
},1)"> 'reject'
});

Promise.all([getData100(),getData200()]).then( [ "100ms","200ms" ]
});

Promise.race([getData100(),getData200(),getData300()]).then( 100ms
});
Promise.resolve('resolve').then('resolve'
})
Promise.reject('reject函数').then((data){
    console.log(data);
},1)">(data){
    console.log(data);     'reject函数'
})
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_68647.html