JavaScript: promise concurrency with Promise.allSettled()

JavaScript: promise concurrency with Promise.allSettled()

In this article we're going to see when it's appropriate to use the Promise.allSettled() method for promise concurrency in JavaScript.

In this article we're going to see when it's appropriate to use the Promise.allSettled() method for promise concurrency in JavaScript.

This method takes an array of Promises and returns an array of values containing one or more objects, each one with three distinct properties:

  1. status: A string that can be either fulfilled or rejected.
  2. value: This property will be available only if status is fullfilled and contain the result of the operation performed by the related Promise.
  3. reason: This property will be available only if status is rejected and contain the reason behind the rejection of the related Promise.

Unlike Promise.all(), Promise.allSettled() won't raise an exception if one or more Promises will be rejected. Instead, it will always return an array with the results of the asynchronous operations performed by the Promises.

So, when it's really appropriate to use this method? The answer is simple: we can use this method when the operations are independent and don't require to be necessarily all successful like those we specify with Promise.all().

Suppose that you're writing a program that pings a series of hosts and returns the results. In this case, it's not necessary that all the URLs must return a successful HTTP status code because the program is designed to also report network problems when they occur.

Promise.allSettled([
    ping('host1.tld'),
    ping('host2.tld'),
    ping('hostN.tld')
]).then((values) => {
        const online = values.filter(v => v.status === 'fulfilled');
        const offline = values.filter(v => v.status === 'rejected');
        
        console.log('Host(s) online', online.length);
        console.log('Host(s) offline', offline.length);
        
        // More details here
});

In short, this method is very useful when the fulfillment of all Promises in a series it's not a requirement for accomplishing a specific task in your project.