Welcome to Abdul Malik Ikhsan's Blog

Handle Promise.allSettled() resolved and each rejected Promise

Posted in Javascript by samsonasik on April 25, 2020

This is a Javascript post! As you probably already knew, that Promise.all() is all or never. How about run all the things even there is/are a rejected promise(s)? There is Promise.allSettled() for that.

The issue is about catching the error for specific promise(s). You CANNOT do this:

await Promise.allSettled(
        [
            promise2,
            promise1,
            promise3
        ]
    )
    .then((results) => results.forEach((result) => {
        // ...
    }))
    .catch(
        // ...
    )
    .finally(
        // ...
    );

As above will only works for Promise.all(), while the resolved promises won’t executed even only there is one promise that rejected.

What you need to do is loop the results, and you will get the result like the following:

On loop, you can check if it has status == ‘rejected’, that a way you know that the promise rejected. The result will always has ‘reason’ key when it rejected, even if the reject value is undefined. So, the code can be:

await Promise.allSettled(
        [
            promise2,
            promise1,
            promise3
        ]
    )   
    .then(
        (results) => {
            for (let result of results) {
                if (result.status == 'rejected') {
                    // handle rejected promise here
                    // eg: make console.log()...
                    console.log('error : ' + result.reason);

                    // continue to next iteration
                    continue;
                }

                // handle fulfilled promise here
                // eg: append in the div
                document.getElementsByClassName('load')[0].innerHTML += result.value + '<br />';
            }
        }
    )
    .finally(
        // ...
    );

That’s it!

References:

Tagged with: ,