Sub topic 12
Edge Cases: Empty Iterables and Plain Values
This chapter assumes you know the four combinators covered earlier: Promise.all, Promise.allSettled, Promise.race, and Promise.any. It also assumes you can use async/await and try/catch. The examples use top-level await, so save them as .mjs files and run them with Node.js 14.8 or later.
Most bugs with combinators come from inputs you did not expect, not from the happy path. A filtered list that ends up empty and an array that mixes plain values with promises are the two most common cases.
Empty Iterables
Each combinator follows its own rule when there is nothing to wait for. Each rule makes sense once you ask what the combinator is waiting for.
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.| Combinator | Empty input result | Why |
|---|---|---|
| `Promise.all` | Fulfills with `[]` | Every one of zero inputs fulfilled |
| `Promise.allSettled` | Fulfills with `[]` | Every one of zero inputs settled |
| `Promise.any` | Rejects with `AggregateError` | No input can ever fulfill |
| `Promise.race` | Stays pending forever | No input can ever settle first |
Promise.all and Promise.allSettled are "every input" checks, and an every-check over nothing is true. Promise.any needs at least one success, so an empty list fails immediately, and its errors array is empty. Promise.race has no input that could settle, so its promise never settles.
A small guard makes the race safe:
function safeRace(promises) {
const list = [...promises];
if (list.length === 0) {
return Promise.reject(new Error('safeRace called with no promises'));
}
return Promise.race(list);
}
try {
await safeRace([]);
} catch (err) {
console.log(err.message); // 'safeRace called with no promises'
}Plain Values and Thenables
Combinators pass every input through Promise.resolve. That has three effects:
- A plain value such as
3or'text'counts as an already-fulfilled promise. - A thenable is any object with a
thenmethod. The combinator adopts its outcome as if it were a real promise. - Results still arrive asynchronously, even when every input is a plain value.
const thenable = { then(resolve) { resolve('from thenable'); } };
const values = await Promise.all([1, thenable, Promise.resolve(3)]);
console.log(values); // [1, 'from thenable', 3]
const slow = new Promise((resolve) => setTimeout(() => resolve('slow'), 100));
console.log(await Promise.race([slow, 'instant'])); // 'instant'
console.log(await Promise.any([Promise.reject(new Error('x')), 42])); // 42In a race, a plain value wins against any promise that is still pending. If several inputs are already settled, the earliest one in input order wins.
Non-Array Iterables and Invalid Input
Combinators accept any iterable, not only arrays. That includes Sets, generators, and strings.
console.log(await Promise.all(new Set([1, 2]))); // [1, 2]
console.log(await Promise.all('ab')); // ['a', 'b']
try {
await Promise.all(42);
} catch (err) {
console.log(err instanceof TypeError); // true
}Strings can cause surprises. If you pass one string where you meant an array of strings, you get its characters back with no error. A non-iterable argument such as 42 does not throw synchronously. The returned promise rejects with a TypeError, so you need await inside try/catch, or a .catch, to see the error.
Exercise
A function runs await Promise.race(urls.filter(isMirror).map(fetch)). In production it sometimes hangs and never logs an error. What causes this, and how do you fix it?
Show answer
When no URL passes the filter, Promise.race receives an empty array and returns a promise that never settles, so the await never continues. Check the filtered array's length first and throw or return early when it is empty, for example with a guard like safeRace.
Exercise
What do await Promise.all(['a', Promise.resolve('b')]) and await Promise.any([]) produce?
Show answer
The first fulfills with ['a', 'b'] because the plain value is treated as already fulfilled. The second rejects with an AggregateError whose errors array is empty.