/proposal-promise-allSettled

ECMAScript Proposal, specs, and reference implementation for Promise.allSettled

Primary LanguageHTML

Promise.allSettled

ECMAScript proposal and reference implementation for Promise.allSettled.

Author: Jason Williams (BBC), Robert Pamely (Bloomberg), Mathias Bynens (Google)

Champion: Mathias Bynens (Google)

Stage: 3

Overview and motivation

There are four main combinators in the Promise landscape.

name description
Promise.allSettled does not short-circuit this proposal 🆕
Promise.all short-circuits when an input value is rejected added in ES2015 ✅
Promise.race short-circuits when an input value is settled added in ES2015 ✅
Promise.any short-circuits when an input value is fulfilled separate proposal 🔜

These are all commonly available in userland promise libraries, and they’re all independently useful, each one serving different use cases.

A common use case for this combinator is wanting to take an action after multiple requests have completed, regardless of their success or failure. Other Promise combinators can short-circuit, discarding the results of input values that lose the race to reach a certain state. Promise.allSettled is unique in always waiting for all of its input values.

Promise.allSettled returns a promise that is fulfilled with an array of promise state snapshots, but only after all the original promises have settled, i.e. become either fulfilled or rejected.

Why allSettled?

We say that a promise is settled if it is not pending, i.e. if it is either fulfilled or rejected. See promise states and fates for more background on the relevant terminology.

Furthermore, the name allSettled is commonly used in userland libraries implementing this functionality. See below.

Examples

Currently you would need to iterate through the array of promises and return a new value with the status known (either through the resolved branch or the rejected branch.

function reflect(promise) {
  return promise.then(
    (v) => {
      return { status: 'fulfilled', value: v };
    },
    (error) => {
      return { status: 'rejected', reason: error };
    }
  );
}

const promises = [ fetch('index.html'), fetch('https://does-not-exist/') ];
const results = await Promise.all(promises.map(reflect));
const successfulPromises = results.filter(p => p.status === 'fulfilled');

The proposed API allows a developer to handle these cases without creating a reflect function and/or assigning intermediate results in temporary objects to map through:

const promises = [ fetch('index.html'), fetch('https://does-not-exist/') ];
const results = await Promise.allSettled(promises);
const successfulPromises = results.filter(p => p.status === 'fulfilled');

Collecting errors example:

Here we are only interested in the promises which failed, and thus collect the reasons. allSettled allows us to do this quite easily.

const promises = [ fetch('index.html'), fetch('https://does-not-exist/') ];

const results = await Promise.allSettled(promises);
const errors = results
  .filter(p => p.status === 'rejected')
  .map(p => p.reason);

Real-world scenarios

A common operation is knowing when all requests have completed regardless of the state of each request. This allows developers to build with progressive enhancement in mind. Not all API responses will be mandatory.

Without Promise.allSettled this is tricker than it could be:

const urls = [ /* ... */ ];
const requests = urls.map(x => fetch(x)); // Imagine some of these will fail, and some will succeed.

// Short-circuits on first rejection, all other responses are lost
try {
  await Promise.all(requests);
  console.log('All requests have completed; now I can remove the loading indicator.');
} catch {
  console.log('At least one request has failed, but some of the requests still might not be finished! Oops.');
}

Using Promise.allSettled would be more suitable for the operation we wish to perform:

// We know all API calls have finished. We use finally but allSettled will never reject.
Promise.allSettled(requests).finally(() => {
  console.log('All requests are completed: either failed or succeeded, I don’t care');
  removeLoadingIndicator();
});

Userland implementations

Naming in other languages

Similar functionality exists in other languages with different names. Since there is no uniform naming mechanism across languages, this proposal follows the naming precedent of userland JavaScript libraries shown above. The following examples were contributed by jasonwilliams and benjamingr.

Rust

futures::join (similar to Promise.allSettled). "Polls multiple futures simultaneously, returning a tuple of all results once complete."

futures::try_join (similar to Promise.all)

C#

Task.WhenAll (similar to ECMAScript Promise.all). You can use either try/catch or TaskContinuationOptions.OnlyOnFaulted to achieve the same behavior as allSettled.

Task.WhenAny (similar to ECMAScript Promise.race)

Python

asyncio.wait using the ALL_COMPLETED option (similar to Promise.allSettled). Returns task objects which are akin to the allSettled inspection results.

Java

allOf (similar to Promise.all)

Dart

Future.wait (similar to ECMAScript Promise.all)

Further reading

TC39 meeting notes

Specification

Implementations