Wait until all promises complete even if some rejected

前端 未结 18 1918
醉酒成梦
醉酒成梦 2020-11-21 04:55

Let\'s say I have a set of Promises that are making network requests, of which one will fail:

// http://does-not-exist will throw a TypeError
va         


        
18条回答
  •  被撕碎了的回忆
    2020-11-21 05:35

    Update, you probably want to use the built-in native Promise.allSettled:

    Promise.allSettled([promise]).then(([result]) => {
       //reach here regardless
       // {status: "fulfilled", value: 33}
    });
    

    As a fun fact, this answer below was prior art in adding that method to the language :]


    Sure, you just need a reflect:

    const reflect = p => p.then(v => ({v, status: "fulfilled" }),
                                e => ({e, status: "rejected" }));
    
    reflect(promise).then((v => {
        console.log(v.status);
    });
    

    Or with ES5:

    function reflect(promise){
        return promise.then(function(v){ return {v:v, status: "fulfilled" }},
                            function(e){ return {e:e, status: "rejected" }});
    }
    
    
    reflect(promise).then(function(v){
        console.log(v.status);
    });
    

    Or in your example:

    var arr = [ fetch('index.html'), fetch('http://does-not-exist') ]
    
    Promise.all(arr.map(reflect)).then(function(results){
        var success = results.filter(x => x.status === "fulfilled");
    });
    

提交回复
热议问题