手写Promise


<script>
    const PENDING="pending";
    const FULFILLED = "fulfiled";
    const REJECTED = "rejected";
    function MyPromise(fn){
        let _this=this;
        _this.state=PENDING;
        _this.value="";
        _this.reason="";
        _this.fulfilledFnArr=[];
        _this.rejectedFnArr=[];
        function resolve(value){
            _this.state=FULFILLED;
            _this.value=value;
            _this.fulfilledFnArr.forEach((item)=>{
                item();
            })
        }
        function reject(reason){
            _this.state=REJECTED;
            _this.reason=reason;
            _this.rejectedFnArr.forEach((item)=>{
                item()
            })
        }
        fn(resolve,reject)
    }

    MyPromise.prototype.then=function(onFulfilledFn,onRejectedFn){
        var _this=this;



        // 针对同步方法
        if(_this.state==FULFILLED){
            console.log("----FULFILLED---")
            return new MyPromise(function(resolve,reject){
                var x = onFulfilledFn(_this.value);
                if(x instanceof MyPromise){
                    x.then(resolve,reject)
                }else{
                    resolve(x)
                }
            })
            
        }
        if(_this.state==REJECTED){
            return new MyPromise(function(resolve,reject){
                var x =  onRejectedFn(_this.reason);
                if(x instanceof MyPromise){
                    x.then(resolve,reject)
                }else{
                    resolve(x)
                }
            })
        }
        // 针对异步方法
        if(_this.state==PENDING){
            return new MyPromise(function(resolve,reject){
            console.log("----PENDING---")
            _this.fulfilledFnArr.push(()=>{
                    var x = onFulfilledFn(_this.value);
                    if(x instanceof MyPromise){
                        x.then(resolve,reject)
                    }else{
                        resolve(x)
                    }
            });
            _this.rejectedFnArr.push(()=>{
                    var x =  onRejectedFn(_this.reason);
                    if(x instanceof MyPromise){
                        x.then(resolve,reject)
                    }else{
                        resolve(x)
                    }
                })
            })
        }
    }



    new MyPromise(function(resolve,reject){
        setTimeout(() => {
            resolve(333)
        }, 5000);
    }).then(function(res){
        console.log(res)
        return new MyPromise(function(resolve,reject){
            setTimeout(() => {
                resolve(8888)
            }, 2000);
        })
    }).then(function(res){
        console.log(res)
    })
    


</script>

 

上一篇:python学习笔记-异常处理


下一篇:js之promise