Sub topic 12
Edge Cases: Empty Iterables and Plain Values
This chapter assumes you already know how Promise.all, Promise.allSettled, Promise.race, and Promise.any behave with ordinary lists of promises. It also assumes you are comfortable with async/await, try/catch, and the idea that promise callbacks run as microtasks. Here we look at the inputs that cause surprises: empty lists, values that are not promises, iterables that are not arrays, and things that are not iterable at all.
To run the examples, save them in a file ending in .mjs so that top-level await works, then run the file with Node.js 16 or later.
How Each Input Is Normalized
All four combinators follow the same first step. They iterate over the input, and they pass every element through Promise.resolve (strictly speaking, the constructor's resolve method). That one rule explains most of the edge cases:
- A native promise comes back unchanged.
- A thenable, meaning any object with a
thenmethod, is adopted. The resulting promise follows whatever thatthenmethod does. - Any other value becomes a promise that is already fulfilled with that value. This covers numbers, strings,
undefined, plain objects, and functions.
Because plain values become fulfilled promises, you can mix cached results with pending work:
const cache = new Map([['a', 'cached A']]);
const load = (key) =>
cache.has(key)
? cache.get(key) // plain value
: new Promise((resolve) => setTimeout(() => resolve(`loaded ${key}`), 50));
const values = await Promise.all(['a', 'b'].map(load));
console.log(values); // ['cached A', 'loaded b']Empty Iterables
An empty input is where the four combinators differ most, and each result follows from the combinator's own rule.
| Combinator | Result for an empty iterable | Why |
|---|---|---|
| `Promise.all([])` | Fulfills with `[]` | "Every input fulfilled" is true when there are no inputs |
| `Promise.allSettled([])` | Fulfills with `[]` | "Every input settled" is also true when there are none |
| `Promise.any([])` | Rejects with `AggregateError`, `errors` is `[]` | No input can ever fulfill, so the combinator fails |
| `Promise.race([])` | Stays pending forever | No input exists that could settle first |
console.log(await Promise.all([])); // []
console.log(await Promise.allSettled([])); // []
try {
await Promise.any([]);
} catch (err) {
console.log(err instanceof AggregateError); // true
console.log(err.errors); // []
}
// Promise.race([]) never settles; awaiting it would wait forever.Empty inputs are rarely written as literal []. They usually come from a filter or a query that found nothing. The Promise.race([]) case is the dangerous one. It throws no error and logs nothing, so the code after the await just never runs. In Node.js, if nothing else keeps the event loop alive, the process exits quietly and skips the rest of the function.
async function firstHealthyMirror(mirrors) {
const candidates = mirrors.filter((m) => m.enabled);
if (candidates.length === 0) {
throw new Error('No enabled mirrors to race');
}
return Promise.race(candidates.map((m) => m.ping()));
}
try {
await firstHealthyMirror([{ enabled: false, ping: async () => 'x' }]);
} catch (err) {
console.log(err.message); // 'No enabled mirrors to race'
}The result of Promise.all([]) is already fulfilled when the call returns. Your then callback or the code after await still runs later, as a microtask. Combinators never call your code synchronously, even when the answer is known right away.
Plain Values Inside race and any
A plain value becomes an already-fulfilled promise, so it beats any input that is still pending. That makes it useful for a default value:
const slow = new Promise((resolve) => setTimeout(() => resolve('network'), 100));
console.log(await Promise.race([slow, 'fallback'])); // 'fallback'When several inputs are already settled, the first one in input order wins. The combinator attaches handlers in iteration order, and the microtasks for already-settled promises run in that same order:
console.log(await Promise.race([1, Promise.resolve(2)])); // 1
console.log(await Promise.any([Promise.reject(new Error('x')), 'y'])); // 'y'
try {
await Promise.race([Promise.reject(new Error('early')), 'value']);
} catch (err) {
console.log(err.message); // 'early'
}The last example shows that race makes no distinction between success and failure. An already-rejected promise placed before a plain value still wins.
Mistakes That Produce Plain Values by Accident
Most surprises with plain values come from bugs, not from deliberate use. The combinator accepts the value and fulfills, so nothing fails loudly.
Passing functions instead of promises
const getUser = async () => ({ id: 1 });
const getOrders = async () => [];
const wrong = await Promise.all([getUser, getOrders]);
console.log(typeof wrong[0]); // 'function', the functions were never called
const right = await Promise.all([getUser(), getOrders()]);
console.log(right); // [{ id: 1 }, []]A function is not a thenable, so the combinator wraps it as a fulfilled value. Nothing runs, and you get the functions back.
Forgetting to return inside map
const ids = [1, 2, 3];
const fetchItem = (id) => new Promise((resolve) => setTimeout(() => resolve(id * 10), 20));
const broken = await Promise.all(ids.map((id) => { fetchItem(id); }));
console.log(broken); // [undefined, undefined, undefined]
const fixed = await Promise.all(ids.map((id) => fetchItem(id)));
console.log(fixed); // [10, 20, 30]The broken version resolves right away with undefined values. The requests are still running in the background, and any rejection from them goes unhandled. A braced arrow body needs an explicit return.
Sparse arrays
Iterating over an array with holes yields undefined for each hole, so Promise.all([, 1]) fulfills with [undefined, 1]. This does no harm, but a hole can hide a missing element.
Iterables That Are Not Arrays
The combinators accept any iterable, so they work with Sets, Map values, generators, and strings.
const set = new Set([Promise.resolve('a'), 'b']);
console.log(await Promise.all(set)); // ['a', 'b']
function* tasks() {
yield Promise.resolve(1);
yield 2;
}
console.log(await Promise.all(tasks())); // [1, 2]
console.log(await Promise.all('hi')); // ['h', 'i']The combinator consumes a generator completely and synchronously at call time. A generator does not let you delay starting work until earlier promises finish. Every task the generator yields has started before Promise.all returns. To limit concurrency you need the worker pattern covered later in this tutorial.
A string is iterable, so a stray string argument does not fail. You get an array of characters instead.
Inputs That Are Not Iterable
If the argument is not iterable, for example undefined, a number, or a plain object, the combinator does not throw synchronously. It returns a promise that rejects with a TypeError:
const p = Promise.all(42); // no exception here
try {
await p;
} catch (err) {
console.log(err instanceof TypeError); // true
}This matters when you call a combinator without await and without attaching catch. The error shows up as an unhandled rejection, not as an exception at the call site.
Thenables That Misbehave
Adoption trusts the object's then method. If then throws, the adopted promise rejects. If then never calls either callback, the adopted promise stays pending, and so does any Promise.all that includes it.
const throwing = { then() { throw new Error('bad thenable'); } };
const silent = { then() {} };
try {
await Promise.all([throwing]);
} catch (err) {
console.log(err.message); // 'bad thenable'
}
const result = await Promise.race([
Promise.all([silent]),
new Promise((resolve) => setTimeout(() => resolve('timed out'), 50))
]);
console.log(result); // 'timed out'Rejections After the Result Is Decided
Each combinator attaches a rejection handler to every input. Suppose Promise.all has already rejected because of one input, and another input rejects later. That later rejection counts as handled, so Node.js does not report it as an unhandled rejection. Its reason is silently dropped. Use Promise.allSettled if you need every reason.
Exercise
What does each line log, or does it never log? (1) console.log(await Promise.all(new Set())) (2) console.log(await Promise.race(['a', Promise.resolve('b')])) (3) console.log((await Promise.allSettled([null]))[0])
Show answer
(1) [], because an empty Set is an empty iterable and Promise.all fulfills with an empty array. (2) 'a', because both inputs are already fulfilled and the first in input order wins. (3) { status: 'fulfilled', value: null }, because null is a plain value and becomes a fulfilled promise.
Exercise
A colleague writes const fastest = await Promise.any(servers.filter(s => s.region === region).map(s => s.query())). In production it sometimes throws an AggregateError whose errors array is empty. What is happening, and how would you fix it?
Show answer
The filter sometimes returns no servers, so Promise.any receives an empty iterable and rejects at once with an empty AggregateError. Check the filtered list's length first and throw a descriptive error, or fall back to another region, before calling Promise.any.
Exercise
Why does await Promise.all([loadConfig, loadUser]) finish instantly without doing any work, and why is Promise.all(undefined) not caught by a try/catch that wraps only the call, without await?
Show answer
loadConfig and loadUser are function references, not promises, so each is wrapped as a fulfilled value and returned without being called. Promise.all(undefined) does not throw synchronously. It returns a promise that rejects with a TypeError, so only awaiting it or attaching catch will see the error.