Promise Combinators

Published by Brayan K

Promise combinators are static methods — Promise.all, allSettled, race, and any — that take an array of promises and combine them into a single promise, letting you coordinate many async operations at once.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Choose a completion rule before starting the work

These methods combine promise outcomes. They do not create threads, decide whether an HTTP response is acceptable, or cancel operations they stop waiting for. Their inputs are iterables, including arrays and Sets. Choose whether the caller needs every success, every outcome, the first settlement or the first success.

function deferred() {
  let resolve, reject;
  const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
  return { promise, resolve, reject };
}
// Register both inputs before either is settled.
const first = deferred(), second = deferred();
const result = Promise.all([first.promise, second.promise]);
// Finish the second input first; ordering still follows the input positions.
second.resolve("B");
first.resolve("A");
console.log(JSON.stringify(await result));

// ✅ Expected output:
// ["A","B"]

Promise.all fulfills only after every input fulfills, and rejects when an input rejection reaches it. The result positions follow iteration order. It does not report how far other work progressed at the moment of rejection. Mastering Promises: Chaining, Error Flow & Patterns owns promise construction and chaining; this lesson owns the aggregate completion rules.

console.log(JSON.stringify(await Promise.all(new Set([Promise.resolve("a"), "b"]))));
console.log(JSON.stringify(await Promise.all([, 3])));

// ✅ Expected output:
// ["a","b"]
// [null,3]
await Promise.all(42);

// ✅ Expected error:
// TypeError: number 42 is not iterable (cannot read property Symbol(Symbol.iterator))

A hole in an array is iterated as undefined and occupies a result position. It is not a skipped job. The JSON display turns that undefined array value into null; the underlying Promise.all result still contains undefined. Validate a task list if holes are not meaningful for your application.

Aggregation does not invoke function values or limit eager starts

let calls = 0;
const jobs = [() => { calls++; return 2; }, () => { calls++; return 3; }];
const untouched = await Promise.all(jobs);
console.log(calls, typeof untouched[0]);
console.log(JSON.stringify(await Promise.all(jobs.map(job => job()))), calls);

// ✅ Expected output:
// 0 function
// [2,3] 2
const started = [];
function work(id) { started.push(id); return Promise.resolve(id * 2); }
const promises = [1, 2, 3].map(work);
console.log(started.join(", "));
console.log(JSON.stringify(await Promise.all(promises)));

// ✅ Expected output:
// 1, 2, 3
// [2,4,6]

The map call invokes every factory immediately. Promise.all receives the already-created promises. To bound how many jobs are active, keep factories uncalled until a slot is free; the independent brief implements that policy. Concurrent waiting is different from CPU parallelism. Web Workers (Background Threads) owns background execution.

An early aggregate rejection does not undo or stop siblings

function deferred() {
  let resolve, reject;
  const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
  return { promise, resolve, reject };
}
const failing = deferred(), remaining = deferred();
const aggregate = Promise.all([failing.promise, remaining.promise]);
const events = [];
const sibling = remaining.promise.then(value => events.push(value));
failing.reject(new Error("first failed"));
try { await aggregate; } catch (error) { console.log(error.message); }
remaining.resolve("still completed");
await sibling;
console.log(events.join(", "));

// ✅ Expected output:
// first failed
// still completed

Attach the aggregate before triggering these controlled rejections. In real code, starting promises and leaving them unobserved while awaiting something else can also produce unhandled rejections. Cancellation needs cooperating operations and a separate policy; AbortController & Cancelling Async Work owns that signal contract. Cancellation still cannot roll back a side effect that has already happened.

allSettled keeps partial success explicit

const results = await Promise.allSettled([
  Promise.resolve("profile"),
  Promise.reject(new Error("avatar missing")),
  undefined
]);
console.log(JSON.stringify(results.map(result => result.status === "fulfilled"
  ? { status: result.status, value: result.value ?? "(undefined)" }
  : { status: result.status, reason: result.reason.message })));

// ✅ Expected output:
// [{"status":"fulfilled","value":"profile"},{"status":"rejected","reason":"avatar missing"},{"status":"fulfilled","value":"(undefined)"}]

A fulfilled entry has value; a rejected entry has reason. A reason can be any JavaScript value, not necessarily an Error. An aggregate that fulfills with rejected records has not made those underlying jobs successful. Keep the failure information visible instead of replacing every failure with null and losing the distinction.

race and any answer different questions

function deferred() {
  let resolve, reject;
  const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
  return { promise, resolve, reject };
}
const first = deferred(), second = deferred();
const raced = Promise.race([first.promise, second.promise]);
first.reject(new Error("fast failure"));
second.resolve("later success");
try { console.log(await raced); } catch (error) { console.log(error.message); }

// ✅ Expected output:
// fast failure
function deferred() {
  let resolve, reject;
  const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
  return { promise, resolve, reject };
}
const first = deferred(), second = deferred();
const chosen = Promise.any([first.promise, second.promise]);
first.reject(new Error("not available"));
second.resolve("usable result");
console.log(await chosen);

// ✅ Expected output:
// usable result
function deferred() {
  let resolve, reject;
  const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
  return { promise, resolve, reject };
}
const first = deferred(), second = deferred();
const chosen = Promise.any([first.promise, second.promise]);
second.reject("second reason");
first.reject("first reason");
try { await chosen; }
catch (error) {
  console.log(error.name);
  console.log(JSON.stringify(error.errors));
}

// ✅ Expected output:
// AggregateError
// ["first reason","second reason"]

“First” refers to the outcome observed by the aggregate, not the first array element or an objectively fastest server. If several inputs are already settled, their scheduled reactions and input order matter. A race against a timeout only stops waiting unless the underlying operation is also cancelled. Advanced Fetch API Patterns (Retry, Timeout, AbortController) owns transport and response validation.

try { await Promise.any([]); }
catch (error) { console.log(error.name + ": " + error.message); }

// ✅ Expected output:
// AggregateError: All promises were rejected
let raced = false;
Promise.race([]).then(() => { raced = true; }, () => { raced = true; });
console.log(JSON.stringify(await Promise.all([])));
console.log(JSON.stringify(await Promise.allSettled([])));
console.log(raced);

// ✅ Expected output:
// []
// []
// false

The empty race remains pending. The example observes that state after other microtasks; the permanent pending behavior follows from the operation’s empty-input contract. Even when an aggregate is already fulfilled, a then callback runs asynchronously; an empty all does not make then run inside the current synchronous statement.

Guided exercise: keep both successful and failed outcomes

Use the literal hints to collect every outcome and select successful values. This selection is a deliberate policy; the rejected entries still exist in the original result array.

const results = await Promise.___([Promise.resolve(3), Promise.reject("no"), Promise.resolve(5)]); // 👉 replace ___ with allSettled
const values = results.filter(result => result.status === "___") // 👉 replace ___ with fulfilled
  .map(result => result.___); // 👉 replace ___ with value
console.log(JSON.stringify(values));
console.log(results.length);

// ✅ Expected output:
// [3,5]
// 3

Brief: a bounded pool that returns every outcome

Implement settlePool(jobs, concurrency = 2). Accept a dense array of at most 100 functions and an integer concurrency from 1 through 8. Validate the entire list before invoking any function, then snapshot the factory list. An empty list returns an empty result array.

Start at most concurrency unsettled job invocations at once. Invoke each factory exactly once, with no arguments. A job may return a plain value, a promise or a thenable, or throw synchronously. Return allSettled-shaped records in input order, preserving fulfilled values and rejection reasons. One job failure must not prevent later jobs from starting.

The pool does not add cancellation, a timeout or a retry. A job that never settles keeps its slot and can keep the returned promise pending. This is a concurrency bound for asynchronous work, not a background CPU-thread pool.

async function settlePool(jobs, concurrency = 2) {
  if (!Array.isArray(jobs) || jobs.length > 100) throw new TypeError("expected at most 100 jobs");
  if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 8) {
    throw new RangeError("concurrency must be an integer from 1 to 8");
  }
  for (let i = 0; i < jobs.length; i++) {
    if (!Object.hasOwn(jobs, i) || typeof jobs[i] !== "function") throw new TypeError("jobs must be dense functions");
  }
  const tasks = jobs.slice();
  const results = new Array(tasks.length);
  let cursor = 0;
  async function worker() {
    while (cursor < tasks.length) {
      const index = cursor++;
      try {
        results[index] = { status: "fulfilled", value: await tasks[index]() };
      } catch (reason) {
        results[index] = { status: "rejected", reason };
      }
    }
  }
  await Promise.all(Array.from({ length: Math.min(concurrency, tasks.length) }, () => worker()));
  return results;
}
const events = [];
const result = await settlePool([
  async () => { events.push("a"); return 2; },
  () => { events.push("b"); throw new Error("broken"); },
  () => { events.push("c"); return 5; }
], 2);
console.log(events.join(", "));
console.log(JSON.stringify(result.map(row => row.status === "fulfilled"
  ? [row.status, row.value] : [row.status, row.reason.message])));
let started = 0;
try { await settlePool([() => { started++; }, null], 2); }
catch (error) { console.log(error.name, error.message, started); }

// ✅ Expected output:
// a, b, c
// [["fulfilled",2],["rejected","broken"],["fulfilled",5]]
// TypeError jobs must be dense functions 0

Practice quiz

What does this complete program print? console.log(JSON.stringify(await Promise.all([Promise.resolve("a"), "b"])));

  • ["a","b"]
  • ["b","a"]
  • ["a"]
  • TypeError

Answer: ["a","b"]. Results preserve input order and include plain values.

What does this complete program print? let n=0;const jobs=[()=>++n];const result=await Promise.all(jobs);console.log(n,typeof result[0]);

  • 1 number
  • 0 function
  • 0 number
  • 1 function

Answer: 0 function. Function values are not automatically invoked.

What does this complete program print? const results=await Promise.allSettled([Promise.reject("no"),Promise.resolve(2)]);console.log(results.map(x=>x.status).join(","));

  • fulfilled,fulfilled
  • rejected
  • rejected,fulfilled
  • fulfilled,rejected

Answer: rejected,fulfilled. allSettled records each input outcome in order.

What does this complete program print? console.log(await Promise.any([Promise.reject("no"),Promise.resolve("yes")]));

  • no
  • AggregateError
  • undefined
  • yes

Answer: yes. any seeks the first fulfillment, ignoring rejections unless every input rejects.

What does this complete program print? try{await Promise.race([Promise.reject("no"),Promise.resolve("yes")]);}catch(reason){console.log(reason);}

  • no
  • yes
  • AggregateError
  • undefined

Answer: no. The first queued settlement here is a rejection.

What does this complete program print? try{await Promise.any([Promise.reject("a"),Promise.reject("b")]);}catch(error){console.log(JSON.stringify(error.errors));}

  • ["b","a"]
  • ["a","b"]
  • []
  • ["a"]

Answer: ["a","b"]. AggregateError errors follow input order.

What does this complete program print? const events=[];Promise.all([]).then(()=>events.push("then"));events.push("sync");await Promise.resolve();console.log(events.join(","));

  • then,sync
  • sync
  • sync,then
  • then

Answer: sync,then. A then reaction still runs asynchronously.

What does this complete program print? console.log(JSON.stringify(await Promise.allSettled([])));

  • undefined
  • null
  • AggregateError
  • []

Answer: []. There are no outcomes to collect, so the result is an empty array.

Continue this course

Related lessons