Sunday, 23 April 2017

Error handling in Promise.all in async await syntax

I have some issues to handle multiple rejections in "parallel". How to handle rejection in a async function when we "await in parallel".
Here an example :

function in_2_sec(number) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            reject('Error ' + 3);
        }, 2000);
    }) 
}

async function f1() {
    try {
        let a = in_2_sec(3);
        let b = in_2_sec(30);
        return await a + await b; // awaiting in "parallel"
    } catch(err) {
        console.log('Error', err);
        return false;
    }
}

async function f2() {
    try {
        return await Promise.all([in_2_sec(3), in_2_sec(30)]);
    } catch(err) {
        console.log('Error', err);
        return false;
    }
}

// f1().then(console.log) // UnhandledPromiseRejectionWarning
// f2().then(console.log) // Nice


f1() create a UnhandledPromiseRejectionWarning in node, because the second rejection (b) is not handled.
f2() works perfectly, Promise.all() do the trick, but how to make a f2() with only async/await syntax, without Promise.all() ?



via Smirow

No comments:

Post a Comment