Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling in a Promise.all like flow 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 ' + number);
        }, 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 {
        let a = await Promise.all([in_2_sec(3), in_2_sec(30)]);
        return a[0] + a[1];
    } 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() ?

like image 430
Smirow Avatar asked Apr 23 '17 08:04

Smirow


People also ask

How does promise all handle errors?

Promise. all is all or nothing. It resolves once all promises in the array resolve, or reject as soon as one of them rejects. In other words, it either resolves with an array of all resolved values, or rejects with a single error.

Can we use promise and async await together?

Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.


1 Answers

f2() works perfectly, Promise.all() do the trick, but how to make a f2() with only async/await syntax, without Promise.all()?

Not at all. Use Promise.all! This is what it was made for. Don't think of async/await of replacing promises - you still are using them, it's only syntactic sugar for then calls. There is no syntactic replacement for Promise.all.

Of course it's also possible to re-implement the behaviour of Promise.all yourself (relying on the Promise constructor and .then primitives), but you really don't want to do that (there are too many pitfalls).

like image 163
Bergi Avatar answered Nov 15 '22 14:11

Bergi