Sub topic 3
What a Promise Combinator Does
This chapter assumes you are comfortable with creating promises, chaining then and catch, writing async functions with await, and handling errors with try/catch. It builds on the previous two chapters. The first covered the three promise states. The second showed that starting several promises before awaiting them lets their waiting overlap.
Before looking at the four combinators one at a time, it helps to see what they have in common. Promise.all, Promise.allSettled, Promise.race, and Promise.any all follow the same contract. Once you know that contract, each combinator comes down to one question: when does it settle, and with what?
The Shared Contract: Iterable In, One Promise Out
A promise combinator is a static method on Promise that takes an iterable of inputs and returns a single new promise. All four combinators follow the same steps:
- They iterate the input synchronously, at the moment you call them.
- They pass each element through
Promise.resolve, so plain values and thenables become promises. - They attach fulfillment and rejection handlers to every one of those promises.
- They settle the returned promise exactly once, following their own decision rule.
- They ignore any input that settles after the returned promise has already settled.
The combinators differ only in step 4. The other steps work the same way for all four.
The Four Decision Rules
The table below is the map for the next several chapters. Each row describes one combinator's step 4.
| Combinator | Fulfills when | Rejects when | Fulfillment value | Rejection reason |
|---|---|---|---|---|
| `Promise.all` | every input fulfills | any input rejects | array of values, in input order | the first rejection reason |
| `Promise.allSettled` | every input settles | never, because of its inputs | array of `{ status, value }` or `{ status, reason }` objects, in input order | none |
| `Promise.race` | the first input to settle fulfills | the first input to settle rejects | that input's value | that input's reason |
| `Promise.any` | the first input fulfills | every input rejects | that input's value | an `AggregateError` listing every reason |
Two patterns stand out. all and allSettled wait for a complete set and return arrays in input order. race and any look for a single winner and return one value. Separately, all and race short-circuit on the first rejection or settlement, while allSettled and any keep going through rejections.
Combinators Don't Start Work
People often believe that Promise.all "runs" the tasks you give it. It doesn't. A promise is the result of an operation that has already started. The operation begins when you call the function that creates the promise, such as fetch(url) or setTimeout inside a new Promise. The combinator only watches results that are already on their way.
The following script shows this. Save it as start.mjs and run it with node start.mjs.
const t0 = Date.now();
const log = (msg) => console.log(`${String(Date.now() - t0).padStart(4)} ms ${msg}`);
const delay = (ms, value) =>
new Promise((resolve) => {
log(`start ${value}`);
setTimeout(() => {
log(`finish ${value}`);
resolve(value);
}, ms);
});
const a = delay(200, 'a');
const b = delay(100, 'b');
// Wait before handing the promises to the combinator.
await new Promise((resolve) => setTimeout(resolve, 150));
log('calling Promise.all');
const result = await Promise.all([a, b]);
log(`result ${JSON.stringify(result)}`);The output looks roughly like this:
0 ms start a
0 ms start b
100 ms finish b
150 ms calling Promise.all
200 ms finish a
200 ms result ["a","b"]Both timers started at 0 ms. Promise b had already fulfilled before Promise.all was even called, and the combinator accepted it without trouble. The total time was about 200 ms because the work was already running. The combinator only decided when to report the result.
This has two consequences you will meet again later in the tutorial:
- If you want concurrency, create all the promises first and then pass them in. A combinator can't make sequential code concurrent after the fact.
- A combinator can't stop work either. When
Promise.allrejects early orPromise.racefinds a winner, the other operations keep running. Cancellation needs a separate mechanism, such asAbortController.
Inputs Go Through Promise.resolve
Every element is normalized with Promise.resolve. That gives you three kinds of acceptable input:
- A native promise is used as it is.
- A thenable (any object with a
thenmethod) is adopted, so itsthengets called. - A plain value becomes an already-fulfilled promise.
const thenable = {
then(onFulfilled) {
setTimeout(() => onFulfilled('from thenable'), 10);
}
};
const values = await Promise.all([
Promise.resolve('native'),
thenable,
42
]);
console.log(values); // ['native', 'from thenable', 42]Because of this, you can mix cached values with pending requests in the same array without wrapping anything yourself.
The Input Is Any Iterable, Read Immediately
The input does not have to be an array. Sets, generator objects, and Map.prototype.values() all work. The combinator reads the iterable to the end synchronously, before it returns. For a generator, that means every promise the generator creates is created during the call:
function* requests() {
for (const ms of [30, 10, 20]) {
console.log(`creating ${ms}`);
yield new Promise((resolve) => setTimeout(() => resolve(ms), ms));
}
}
const p = Promise.all(requests());
console.log('Promise.all returned');
console.log(await p); // [30, 10, 20]All three "creating" lines print before "Promise.all returned". The result keeps the order of iteration (30, 10, 20), not the order in which the promises finished.
If the argument is not iterable, the combinator does not throw synchronously. It returns a promise that rejects with a TypeError:
try {
await Promise.all(5);
} catch (err) {
console.log(err instanceof TypeError); // true
}Settling Once, and Handled Rejections
A promise settles only once, and the combinator's output is no exception. When Promise.all has rejected because of input 2, a later rejection from input 4 cannot change the result. Input 4's rejection is still handled, though. The combinator attached a rejection handler to every input in step 3, so Node and browsers do not report it as an unhandled rejection. The combinator passes that handler's result to an output that has already settled, where nothing happens.
The other side of this matters too. A promise you create but never pass to a combinator, never await, and never attach catch to will produce an unhandled rejection warning if it fails. Passing it to a combinator counts as handling it.
A Minimal Model of Promise.all
Writing a simplified combinator makes the contract concrete. This version follows the steps listed at the start of the chapter. It leaves out a few details from the specification, such as using the constructor that all was called on.
function myAll(iterable) {
return new Promise((resolve, reject) => {
const results = [];
let remaining = 0;
let index = 0;
for (const item of iterable) { // step 1: iterate synchronously
const i = index++;
remaining++;
Promise.resolve(item).then( // step 2: normalize
(value) => { // step 3: attach handlers
results[i] = value; // keep input order
remaining--;
if (remaining === 0) resolve(results); // step 4: decision rule
},
reject // first rejection wins
);
}
if (remaining === 0) resolve(results); // nothing to wait for
});
}
const out = await myAll([Promise.resolve(1), 2, new Promise((r) => setTimeout(() => r(3), 20))]);
console.log(out); // [1, 2, 3]Step 5 comes for free. Calling resolve or reject on a promise that has already settled does nothing. The counter logic is safe because then callbacks always run asynchronously, so remaining reaches its full count before any callback can decrease it. A thrown error during iteration happens inside the executor, which turns it into a rejection, the same behavior shown in the TypeError example.
To get the other three combinators, change the handlers. allSettled records { status, value } or { status, reason } objects and never calls reject. race passes resolve and reject directly to each input. any counts rejections instead of fulfillments. The following chapters cover each one in detail.
Exercise
A function calls const p1 = fetchUser(); await sleep(1000); const p2 = fetchOrders(); await Promise.all([p1, p2]);. Each fetch takes about 500 ms. Roughly how long does the whole function take, and why doesn't Promise.all make it faster?
Show answer
About 1500 ms. fetchUser starts at 0 ms and finishes at about 500 ms. fetchOrders doesn't start until after the 1000 ms sleep, so it finishes at about 1500 ms. Promise.all only waits on promises that already exist. It can't start fetchOrders earlier, because the operation begins when fetchOrders() is called.
Exercise
What does await Promise.all(new Set([Promise.resolve('x'), 'y'])) produce, and what happens with Promise.race(null) if you never attach a handler to it?
Show answer
The first produces ['x', 'y']. A Set is iterable, and the plain value 'y' is passed through Promise.resolve. The second returns a promise that rejects with a TypeError, because null is not iterable. With no handler attached, this surfaces as an unhandled rejection instead of a synchronous throw.
Exercise
In the myAll model, why is it safe to check remaining === 0 inside the fulfillment handler even though remaining is still being incremented by the loop?
Show answer
Promise reaction callbacks always run asynchronously, as microtasks, after the current synchronous code finishes. The loop finishes counting every input before any fulfillment handler runs. So remaining can't drop to 0 too early, even for inputs that are already fulfilled.