Wait until all promises complete even if some rejected

前端 未结 18 1960
醉酒成梦
醉酒成梦 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:44

    I think the following offers a slightly different approach... compare fn_fast_fail() with fn_slow_fail()... though the latter doesn't fail as such... you can check if one or both of a and b is an instance of Error and throw that Error if you want it to reach the catch block (e.g. if (b instanceof Error) { throw b; }) . See the jsfiddle.

    var p1 = new Promise((resolve, reject) => { 
        setTimeout(() => resolve('p1_delayed_resolvement'), 2000); 
    }); 
    
    var p2 = new Promise((resolve, reject) => {
        reject(new Error('p2_immediate_rejection'));
    });
    
    var fn_fast_fail = async function () {
        try {
            var [a, b] = await Promise.all([p1, p2]);
            console.log(a); // "p1_delayed_resolvement"
            console.log(b); // "Error: p2_immediate_rejection"
        } catch (err) {
            console.log('ERROR:', err);
        }
    }
    
    var fn_slow_fail = async function () {
        try {
            var [a, b] = await Promise.all([
                p1.catch(error => { return error }),
                p2.catch(error => { return error })
            ]);
            console.log(a); // "p1_delayed_resolvement"
            console.log(b); // "Error: p2_immediate_rejection"
        } catch (err) {
            // we don't reach here unless you throw the error from the `try` block
            console.log('ERROR:', err);
        }
    }
    
    fn_fast_fail(); // fails immediately
    fn_slow_fail(); // waits for delayed promise to resolve
    

提交回复
热议问题