Skip to the solution
MediumDSA6 min read

Implement Promise.any() with AggregateError

870 views

The problem

Problem, as an interviewer would state it: "Implement Promise.any(promises) — resolving with the value of the FIRST promise to fulfill, and REJECTING with a real AggregateError (containing every individual rejection reason) only if EVERY promise rejects, matching real native Promise.any's own documented contract."

Examples:

Code
Promise.any([Promise.reject("x"), Promise.resolve("y")]); // resolves "y"
Promise.any([Promise.reject("a"), Promise.reject("b")]);  // rejects AggregateError

Clarifying questions expected:

  • How does this genuinely differ from Promise.race — does an EARLIER rejection need to be correctly ignored if a LATER promise still fulfills?
  • What real, specific error type should be thrown when every promise rejects — a plain Error, or the real, dedicated AggregateError?
  • What is the real, correct behavior for a genuinely empty input array?

Code / implementation expected: Yes — real, direct proof it resolves on the first fulfillment despite an earlier rejection, and throws a real AggregateError (populated with every individual rejection reason) only when every promise genuinely rejects.

  • promise
  • promiseAny
  • aggregateError

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the Promise.any polyfill resolves on the first fulfillment despite an earlier rejection, and correctly throws a real AggregateError when every promise rejects

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 97 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement TimeLimitedCache (LeetCode 2622) with expiry

Continue