Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I error handle await Promise.all with a try-catch block?

Tags:

javascript

I have the following piece of code:

    const [games, songs] = await Promise.all([
        getGames(),
        getSongs(),
    ]);

but currently errors are not handled in any way. Would it be correct to surround that piece of code with try-catch like this:

    try {
        const [games, songs] = await Promise.all([
            getGames(),
            getSongs(),
        ]);
    } catch (error) {
        // error handle
    }
like image 381
Bobimaru Avatar asked Oct 16 '25 02:10

Bobimaru


1 Answers

try/catch is a correct way to catch errors from Promise.all, but at the same time, it will ignore all fulfilled requests once only a single request failed, which is not ideal if you still want to have other successful requests' data instead of logging errors, so I'd suggest you use Promise.allSettled

With this solution, it will keep all requests including failed ones and successful ones

const [groupedMeditations, meditationPreferences] = await Promise.allSettled([
   getMeditationsByGroup(),
   getAllPreferences(),
]);

A possible result can be

[
   {status: "fulfilled", value: "successful value"}, // your 1st request passed
   {status: "rejected",  reason: "Error: an error"} //your 2nd request failed
]

From that response, you can filter or log errors

Just one side note that Promise.allSettled does not work for IE, so you need to have polyfill to overcome that

Hopefully, it's helpful for your case :D

like image 162
Nick Vu Avatar answered Oct 18 '25 14:10

Nick Vu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!