Introducing Promice.any()

Introducing Promice.any()

2 Aug 2020 promises javascript

Firefox version 79 just launched. As this Register article points out, while it's not exactly loaded with new features for regular web users it comes with a bunch of goodies for us developers.

One of the more notable additions is support for Promise.any(). This method is still considered 'experimental' as browser support is still thin on the ground, but it stands to become really quite useful.

Bit hazy on the Promises API? Check out my in-depth guide to them.

It works similarly to Promise.race(), except where Promise.race() will quit as soon as the fastest promise fed to it is fulfilled OR rejected, Promise.any() quits only when a promise is fulfilled.

Let's see the difference in action.

let proms = [Promise.reject('foo'), Promise.resolve('bar')]; Promise.race(proms).then( val => alert('Fulfilled with '+val), reason => alert('Rejected with '+reason) ); //produces "Rejected with foo

For the purposes of illustration, so we know which promise will be fastest, I'm using promises that are immediately resolved here (via Promise.resolve() / Promise.reject()). Obviously in a real scenario we'd be working with promises that are resolved after an indeterminate period of time.

Here, the first promise to resolve one way or the other is rejected. Promice.race() is fine with this, stops waiting and is resolved (with a rejection).

Let's run the same code but with Promise.any().

Promise.any(proms).then( ... ); //produces "Resolved with bar"

Promise.any() is interested only in promises that are fulfilled, remember, so although the promise that fulfils isn't the fastest promise, it's the only one it cares about. The faster promise, which is rejected, is ignored.

If none of the promises are fulfilled, and we don't provide an error handled, we get the usual "Uncaught (in promise)..." error, but with the addendum "AggregateError: No Promise in Promise.any was resolved".

This is a great addition. With race conditions you're usually going to want to know about the first promise to be fulfilled, not merely resolved either way, so this looks like it'll be very useful once browser support is more broad.

Did I help you? Feel free to be amazing and buy me a coffee on Ko-fi!