Skip to content
jshacks.dev
Functions

Implement Promise.any From Scratch in JavaScript

Implement Promise.any from scratch in JavaScript so it fulfills with the first success and rejects with an AggregateError when every input fails. Node.js 24.

8 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, Vite, Node.js and TypeScript logos.

Promise.any(iterable) is the mirror image of Promise.all. It fulfills as soon as the first input fulfills, ignoring any rejections before that, and it rejects only when every input has rejected, with an AggregateError that holds all the reasons. It arrived in ES2021 to answer the question race cannot: give me the first thing that works. The implementation is a counter of failures instead of successes, and the details are the error type, the order of the collected errors, the empty input, which rejects at once, and what happens to the inputs that lose. This post builds promiseAny on Node.js 24, step by step with output, and shows the use cases: mirrors, fallbacks and the first valid answer. The related functions are Promise.race, Promise.all and Promise.allSettled.

The behavior to match

JavaScript
const delay = (value, ms) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (message, ms) => new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));

console.log(await Promise.any([fail("mirror 1 down", 5), delay("mirror 2", 20), delay("mirror 3", 40)]));

try {
  await Promise.any([fail("first", 5), fail("second", 10)]);
} catch (error) {
  console.log(error.name, error.errors.map((e) => e.message));
  console.log(error instanceof AggregateError, error.message);
}

try {
  await Promise.any([]);
} catch (error) {
  console.log(error.name, error.errors);
}
Text
mirror 2
AggregateError [ 'first', 'second' ]
true All promises were rejected
AggregateError []

The first call skips the early failure and returns the first success, mirror 2. The second rejects only when both inputs have failed, with an AggregateError. Its errors property lists the reasons in input order, and the message is a fixed string chosen by the engine, which you should not match in tests. An empty input has no success to wait for, so it rejects at once with an empty errors list.

The implementation

Count the failures, store each reason at its index, and reject with an AggregateError when all inputs have failed. Resolve on the first fulfillment.

JavaScript
function promiseAny(iterable) {
  return new Promise((resolve, reject) => {
    if (iterable == null || typeof iterable[Symbol.iterator] !== "function") {
      reject(new TypeError(`${String(iterable)} is not iterable`));
      return;
    }

    const items = [...iterable];

    if (items.length === 0) {
      reject(new AggregateError([], "All promises were rejected"));
      return;
    }

    const errors = new Array(items.length);
    let remaining = items.length;

    items.forEach((item, index) => {
      Promise.resolve(item).then(resolve, (reason) => {
        errors[index] = reason;
        remaining -= 1;

        if (remaining === 0) {
          reject(new AggregateError(errors, "All promises were rejected"));
        }
      });
    });
  });
}

console.log(await promiseAny([fail("a", 5), delay("b", 20), delay("c", 40)]));

try {
  await promiseAny([fail("first", 10), fail("second", 5)]);
} catch (error) {
  console.log(error.constructor.name, error.errors.map((e) => e.message));
}
Text
b
AggregateError [ 'first', 'second' ]

The structure mirrors all with the roles swapped: the success handler is the outer resolve, so the first fulfillment wins and later ones are ignored, and the failure handler records the reason and counts down. Reasons are stored by index, so the errors array follows the input order, first then second, even though second failed earlier in time.

AggregateError is a built-in error class from ES2021 that wraps several errors. Its constructor takes an iterable of errors and an optional message, and exposes them as the errors property. It is available in Node.js 15 and later and in current browsers.

JavaScript
const aggregate = new AggregateError([new Error("a"), new TypeError("b")], "two things failed");

console.log(aggregate.name, aggregate.message, aggregate.errors.length);
console.log(aggregate.errors.map((e) => e.name));
Text
AggregateError two things failed 2
[ 'Error', 'TypeError' ]

Non-promise values

A plain value counts as an immediate success, so it wins against pending promises.

JavaScript
console.log(await promiseAny([fail("x", 5), "plain"]));
console.log(await promiseAny([Promise.reject(new Error("no")), delay("yes", 5)]));
Text
plain
yes

The first call finishes in the next microtask with the plain string. The second ignores the instant rejection and waits 5 ms for the success. In both, the Promise.resolve(item) wrapper is what treats values and promises the same way.

Why not use race, and why not all

race returns the first settlement, so a quick failure beats a slower success. That is wrong when you want the first usable answer.

JavaScript
const viaRace = await Promise.race([fail("mirror 1 down", 5), delay("mirror 2", 20)]).catch((e) => e.message);
const viaAny = await promiseAny([fail("mirror 1 down", 5), delay("mirror 2", 20)]);

console.log(viaRace, "|", viaAny);
Text
mirror 1 down | mirror 2

all needs every input to succeed, which is the opposite requirement. So the choice among the four combinators is about what success means for your problem: all must succeed (all), report on every outcome (allSettled), any outcome ends it (race), or one success is enough (any).

A fallback chain

A common use is trying alternatives and taking the first that works: several mirrors of a file, several endpoints for an API, several caches.

JavaScript
const sources = {
  primary: () => fail("primary offline", 5),
  secondary: () => delay("data from secondary", 15),
  tertiary: () => delay("data from tertiary", 30),
};

const data = await promiseAny(Object.values(sources).map((load) => load()));

console.log(data);
Text
data from secondary

All the sources start together, and the answer comes from the fastest one that works. If you want them tried in order, one after another, so that backups are only used when needed, that is a loop and not any, because any starts everything at once and wastes the requests that lose.

JavaScript
async function firstSuccessful(loaders) {
  const errors = [];

  for (const load of loaders) {
    try {
      return await load();
    } catch (error) {
      errors.push(error);
    }
  }

  throw new AggregateError(errors, "All sources failed");
}

console.log(await firstSuccessful([() => fail("a", 1), () => delay("b is fine", 1)]));
Text
b is fine

The loop is sequential on purpose: the second loader only starts if the first fails.

Losers are not cancelled

As with race, the other inputs keep running. If a mirror download is slow, it continues after a faster one wins. Pass an AbortSignal into each task and abort it once the first success arrives, as described in the post on race.

JavaScript
async function anyWithCancel(tasks) {
  const controller = new AbortController();

  try {
    return await promiseAny(tasks.map((task) => task(controller.signal)));
  } finally {
    controller.abort();
  }
}

const stopped = [];

const task = (name, ms) => (signal) =>
  new Promise((resolve) => {
    const timer = setTimeout(() => resolve(name), ms);

    signal.addEventListener("abort", () => {
      clearTimeout(timer);
      stopped.push(name);
    });
  });

console.log(await anyWithCancel([task("fast", 5), task("slow", 50)]));
console.log(stopped);
Text
fast
[ 'fast', 'slow' ]

The finally aborts after the winner is known. The abort listener of the winner also fires, since its timer has already fired and the listener is still attached, so stopped contains both names. That detail shows that cleanup code must tolerate being called for a task that has already finished. In a real task, you would remove the listener when the work completes.

Handling the AggregateError

When every input fails, the useful information is in errors, and the top-level message tells you very little. Log or report each entry with the input that produced it. Because the order matches the input order, you can pair the reasons with the sources by index, which turns "all promises were rejected" into "mirror one timed out, mirror two returned a 404, mirror three refused the connection".

Be careful when you test the error. The AggregateError is an object with an errors array, so assert.deepEqual on the whole error compares more than you probably intend, and the message text belongs to the engine. Check the type with instanceof AggregateError, and check the list of reasons separately. If you wrap the call in a function of your own, decide whether to rethrow the aggregate as it is or to translate it into your own error class, and do it in one place so callers handle one kind of failure.

One more detail concerns unhandled rejections. When the first input fulfills, the remaining inputs may still reject later. Each of them has the failure handler attached by our implementation, so none is reported as unhandled, and the native Promise.any does the same. If you wrote a version that attached a handler only to the winner, a late failure would crash the process in Node.js 24, which treats an unhandled rejection as a fatal error by default.

Choosing the combinator

A short decision process works well in practice. Ask what should happen when one input fails. If the whole operation fails, because the results depend on each other, use all. If you need a report of every outcome, use allSettled. If a failure should end the wait just like a success does, as in a timeout, use race. If a failure should be ignored while some other input might still work, use any.

Then ask what you want to do with the results. all and allSettled give you one value per input. race and any give you one value in total, and discard the rest. If you need the first few successes and not just one, none of the four fits, and you want a loop over an async iterator or a small helper that counts successes and resolves at a threshold.

The decision also depends on the cost of the losing inputs. Because none of the combinators cancels the inputs that lose, using any over expensive operations, such as large downloads from several mirrors, wastes bandwidth unless you also pass an AbortSignal. For cheap operations, such as checking several caches, the waste does not matter and any is the simplest tool.

Tests

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("promiseAny takes the first fulfillment", async () => {
  assert.equal(await promiseAny([fail("x", 1), delay("ok", 5)]), "ok");
});

test("promiseAny rejects with all reasons in input order", async () => {
  await assert.rejects(promiseAny([fail("first", 10), fail("second", 1)]), (error) => {
    assert.ok(error instanceof AggregateError);
    assert.deepEqual(error.errors.map((e) => e.message), ["first", "second"]);

    return true;
  });
});

test("promiseAny rejects for an empty input", async () => {
  await assert.rejects(promiseAny([]), AggregateError);
});
Text
ℹ tests 3
ℹ pass 3
ℹ fail 0

How to present it

Say that it is the inverse of all in the sense that matters: all stops on the first failure, and any stops on the first success. Write the structure of all with the handlers swapped, and then add the three details: the AggregateError, the ordered list of reasons and the empty input rejecting. A good closing remark is the difference from race, since it shows that you pick the combinator by the meaning of success.

Also inAsync
Taggedinterview
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.