I’ve recently read the Promise combinators article in v8 blog. It's about two upcoming methods in Promise API: Promise.allSettled() and Promise.any(). And I feel frustrated. The design of these methods looks to me inconsistent with current Promise API. Let me share my opinion below.
According to article:
Promise.allSettled gives you a signal when all the input promises are settled, which means they're either fulfilled or rejected.
The use-case is to send several API calls and wait for all finished:
const promises = [
fetch('/api-call-1'),
fetch('/api-call-2'),
fetch('/api-call-3'),
];
await Promise.allSettled(promises);
removeLoadingIndicator();
For sure, this is useful. But this task can be easily solved with .map() and Promise.all(). The change is minimal:
const promises = [
fetch('/api-call-1'),
fetch('/api-call-2'),
fetch('/api-call-3'),
].map(p => p.catch(e => e)); // <-- the only change
await Promise.all(promises);
removeLoadingIndicator();
Is it worth implementing a new core method that can be solved in a few lines of code? As for me this is a library-land feature, not the core API method.
But more important is that Promise.allSettled brings extra level of abstraction. Unlike Promise.all it fulfills with array of wrapping objects {status, reason} instead of pure promise values. As a developer I don’t like it. I expect that methods with similar names .all()/.allSettled() behave similar ways. But they don’t.
Moreover, the code with Promise.allSettled encourages late errors handling. Errors supposed to be filtered out from the final result instead of traditional catch block. This, in turn, has the following downsides:
Using current Promise.all you avoid such things.
Promise.any gives you a signal as soon as one of the promises fulfills.
In other words Promise.any is Promise.race that ignores rejections.
The use-case is to check several endpoints and take data from the first successful one:
const promises = [
fetch('/endpoint-a').then(() => 'a'),
fetch('/endpoint-b').then(() => 'b'),
fetch('/endpoint-c').then(() => 'c'),
];
try {
const first = await Promise.any(promises);
} catch (error) {
// All of the promises were rejected.
console.log(error);
}
I agree sometimes it may be useful. But how often? In how many projects did you use the pattern “make several parallel requests to identical endpoints for the same data”? Feel free to share in comments. But from my vision — not very often. Couldn’t it be more useful for community to get native implementation of bluebird’s Promise.each() or Promise.delay() ?
Moreover, Promise.any introduces a new type of error — AggregateError. Such error contains links to other errors if all promises are rejected. One more error handling approach! It differs from Promise.allSettled where errors are extracted from success result. It also differs from Promise.all/Promise.race which reject with just an Error instance. How will JavaScript look like if every new Promise API method will introduce new way of error handling? Although the proposal is on a very early stage, I’m concerned about the direction.
Based on current Promise API the implementation of Promise.any is a bit tricky but actually two lines of code:
const reverse = p => new Promise((resolve, reject) => Promise.resolve(p).then(reject, resolve));
Promise.any = arr => reverse(Promise.all(arr.map(reverse)));
Maybe keep it in library-land?
Why Promise.all and Promise.race are so pretty?
Because they behave very consistent and similar to usual promises: fulfill with just a value and reject with just an error. No wrapped values, no accumulated errors, no extra complexity.
Why Promise.allSettled and Promise.any are so weird to me?
Promise.allSettled fulfills with array of objects with status and reason wrapping underlying promise values. And rejects… never.
Promise.any fulfills with a single value but ignores intermediate rejections. Only if all promises are rejected it rejects with accumulated reason wrapping all underlying reasons.
These new approaches are really difficult to put in my head. As they are quite different from the current Promise API.
I suppose a popular job interview question in 2020:
What’s the difference of these four methods?
Although it’s cool question I don’t think core API should encourage such complexity.
I’m also disappointed with naming. Four methods with slightly different behavior should have pretty clear names. Otherwise I have to re-check MDN every time I meet them in code. From the proposal of Promise.any:
Let me to disagree. For me the name of Promise.any is confusing:
I think, the name of each method should explicitly define the condition when the method fulfills. I would suggest the following naming convention:
Promise.all -> Promise.allFulfilled
Promise.allSettled -> Promise.allSettled
Promise.race -> Promise.oneSettled
Promise.any -> Promise.oneFulfilled
It reflects four possible combinations of promise states. It explains why these methods are referenced as combinators in proposal.
Of course, such rename is not possible as Promise.all and Promise.race already landed and used in many applications. But for new methods having some naming strategy would be very helpful.
I've opened issue in Promise.any proposal repository on GitHub, you are welcome to share you thoughts.
In general I'm not inspired with the concept of non-thrown “swallowed” rejections. In fact, new Promise API provides a way to silently ignore errors in the code:
Currently no other core JavaScript API does that. The only way to ignore an error — manually wrap it into try..catch/.catch() with empty body. And write a comment why do you ignore error here, otherwise eslint will warn you.
I think the core API should expose all errors. It is always a developer decision whether to handle error or not. It should be explicit for other developers reading the code. Just imagine how many hours of debugging will be spent due to inaccurate usage of swallowed rejections! Especially when dealing with third-party code— when something does not work and no errors thrown.
I use promises every working day. As well as many other developers do. I love JavaScript for its async nature. Having clear and intuitive API allows me to solve tasks faster and be more productive. That’s why I think Promise API should be treated and changed very carefully.
Thanks for reading and welcome to comments.