美文网首页
实现Promise.all Promise.race

实现Promise.all Promise.race

作者: Time_Notes | 来源:发表于2020-07-08 16:45 被阅读0次

    Promise.all = (promises) => {

        let results=[];

        return new Promise((resolve,reject)=>{

            let i=0;

            while(i<promises.length){

                promises[i].then(res=>{

                    results.push(res);

                    i++;

                    if(i===promises.length){resolve(results);}

                }).catch(err=>{

                    reject(err); //只要有任何Promise出现reject,Promise.newAll就直接reject

                });

            }

        })

    }

    如果想捕获promise.all的错误又想返回怎么办

    手写Promise.All,并且在这个All中加一个超时时间

    1、使用setTimeout方式,在一个promise.all中设置。

    2、将setTimeout封装成promise,然后使用promise.race来输出最快的promise


    实现Promise.race

    Promise.race = function(promises){

        return new Promise((resolve,reject) => {

            let i=0;

            while(i<promises.length){

                promises[i].then(res=>{

                    resolve(res); //出现第一个被resolve的直接resolve

                }).catch(err=>{

                    reject(err); //出现第一个被reject的直接reject

                });

                i++;

            }

        })

    }

    js实现并发多个请求,返回先得到response的,类似Promise.race的实现


    要求1:按以下要求输出

    human('Jack').eat().sleep(5).go().rest(10);

    // I am Jack

    // Eat

    // 等 5 秒

    // Sleep 5s

    // Go

    // 等 10 秒

    // Rest 10s

    要求2:eat/sleep/go/rest可以改变任意顺序human('Jack').sleep(5).eat().rest(10).go();

    function human(name){

        return new Human(name)

    }

    function Human(name){

        this.name=name

        this.sayHello()

        this.queue=Promise.resolve()

    }

    Human.prototype.sayHello=function(){

        console.log(`I am ${this.name}`)

    }

    Human.prototype.eat=function(){

        this.queue = this.queue.then(()=>{

            return new Promise((resolve)=>{

                console.log('Eat') 

                resolve()})

            })

            return this

    }

    Human.prototype.sleep=function(time){

        this.queue=this.queue.then(()=>{

            return new Promise((resolve)=>{

                setTimeout(()=>{

                console.log(`Sleep ${time}s`)

                resolve()},time*1000)

            })

        })

        return this

    }

    Human.prototype.go=function(){

        this.queue=this.queue.then(()=>{

            return new Promise((resolve)=>{

                console.log('Go')

                resolve()

            })

        })

        return this

    }

    Human.prototype.rest=function(time){

        this.queue=this.queue.then(()=>{

            return new Promise((resolve)=>{

                setTimeout(()=>{

                console.log(`Rest ${time}s`);

                resolve()},time*1000)

            })

        })

        return this

    }

    human('Jack').eat().sleep(5).go().rest(10);


    function cancelableXHR(URL){

        var req=newXMLHttpRequest();

        var promise=new Promise((resolve,reject)=>{

            req.open('GET',URL,true);

            req.onload=function(){

                if(req.status===200){resolve(req.responseText);}

                else{reject(new Error(req.statusText));}

            };

            req.onerror=function(){reject(new Error(req.statusText));};

            req.onabort=function(){reject(new Error('abort this request'));};

            req.send();

        });

        var abort=function(){

            if(req.readyState!==XMLHttpRequest.UNSENT){req.abort();}

        };

        return{

            promise:promise,

            abort:abort

        };

    }

    相关文章

      网友评论

          本文标题:实现Promise.all Promise.race

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