⚡ JavaScript: Fix Array.prototype.flat Not Flattening a Nested Array Returned From an Async Map Because the Outer Array Still Holds Unresolved Promises Instead of Arrays
Array.prototype.map with an async callback doesn’t wait for each callback to resolve before moving to the next element — it immediately returns a Promise from every call, so the array map produces is an array of Promises, not an array of whatever your async function eventually resolves to. Calling flat() on that array sees exactly what’s there: a flat array of Promise objects, none of which are themselves arrays, so there’s nothing for flat() to flatten yet.
🔎 The Problem
const nested = items.map(async item => {
const related = await fetchRelatedIds(item);
return related; // resolves to an array, e.g. [1, 2, 3]
});
console.log(nested);
// [Promise, Promise, Promise] - NOT [[1,2,3], [4,5], ...]
const flat = nested.flat();
// still [Promise, Promise, Promise] - flat() sees Promises,
// not arrays, so there's nothing to flatten yet
✅ Fix: Await the Promises First, Then Flatten the Resolved Array
- Await all the Promises first with
Promise.all(nested)to get the actual array of arrays, and only call flat() on that resolved result. - Reach for flatMap only when your callback is synchronous; for an async callback there is no single built-in that both awaits and flattens in one call, so the explicit two-step pattern is the correct choice rather than something to work around.
- Add a quick runtime check in development confirming no element of the mapped array is itself still a Promise right before any flat() or flatMap() call that might receive async-mapped input, so this mistake fails loudly in testing instead of silently returning pending Promises in production.
🚨 Why This Is Dangerous
- Because nested.flat() doesn’t throw — it just returns an array of Promises that still looks array-shaped — this bug can pass code review and even casual testing if nobody happens to log or inspect an individual element, surfacing only once something downstream tries to use a value and gets a Promise object instead of real data.
map with an async callback gives you an array of promises to deal with, not an array of answers — flat() can only flatten what’s already there, and promises aren’t arrays.
