Which Promise method should I use?
Practice this questionDefinition:
Promise combinators combine several promises into one result. The correct method depends on whether you need every success, every outcome, the first outcome or the first success. They observe promises; they do not automatically cancel ongoing operations when the combined result settles.
Key points:
-
all: need every result; rejects when one rejects, but does not cancel the others. -
allSettled: need the result of every task, including failures. -
race: first settled result.any: first success, or rejection if all fail. -
Promise.allkeeps results in input order, even if the operations finish in a different order. -
Promise.anyrejects with anAggregateErrorif every input rejects. -
A timeout implemented with
raceonly stops waiting; cancel the underlying operation separately when supported.
Comparison:
| Method | Successful result | Failure behavior |
|---|---|---|
all | All fulfilled values in input order | Rejects on an input rejection |
allSettled | Status/result for every input | Input rejection becomes a result item |
race | First settled input's outcome | Rejects if first settled input rejects |
any | First fulfilled value | Rejects if all inputs reject |
Interview point:
- State what happens on failure as well as on success, and mention concurrency limits for large input lists.