Why Promise.all Results Get Mixed Up
Promise.all preserves input order, but positional destructuring can misassign results after refactors. See how typed keyed helpers prevent mix-ups and where Promise.allKeyed stands.
Native Promise.all always returns results in the order you passed the promises in, so when values end up in the wrong variable, the cause is destructuring that no longer matches that order.
This kind of bug survives code review. A loader gets one more request added, the tests that cover it still pass, and a page shows a company name where the user’s theme should be.
This article shows the refactor that causes it, explains why the native method is not at fault, and gives you typed keyed helpers you can use today. It also covers the TC39 proposal that adds keyed versions of these methods to the language.
Key Takeaways
Promise.allnever reorders its results: the fulfilled array follows the order of the input promises, not the order in which they settled.- When a refactor adds or moves a promise without updating the array destructuring, values shift into the wrong variables and nothing throws.
- TypeScript catches a misaligned destructuring only where a shifted value is used, and only if the swapped values have different shapes.
- If you pass an object of promises instead of an array, each result stays tied to its name, so reordering requests cannot misalign them.
Promise.allKeyedandPromise.allSettledKeyedare at Stage 3 in TC39. Firefox 155 ships them natively, and other engines need a polyfill from core-js or es-shims.
The Refactor Bug: Values Shift With No Error
Positional destructuring breaks silently when someone inserts a promise in the middle of the array. The code below runs as an ES module because it uses top-level await:
type User = { id: string; name: string };
type Company = { id: string; name: string };
type Settings = { theme: "light" | "dark" };
const getUser = async (id: string): Promise<User> => ({ id, name: "Ada" });
const getCompany = async (id: string): Promise<Company> => ({ id, name: "Acme" });
const getSettings = async (_id: string): Promise<Settings> => ({ theme: "dark" });
// Before: correct
const [user, company] = await Promise.all([getUser("1"), getCompany("1")]);
// After a refactor: getSettings inserted in the middle, the new name appended at the end
const [user2, company2, settings2] = await Promise.all([
getUser("1"),
getSettings("1"),
getCompany("1"),
]);
console.log(company2.name); // TS error: Property 'name' does not exist on type 'Settings'
company2 now holds the settings object and settings2 holds the company. TypeScript does not report an error on the destructuring line. It infers each variable’s type from its position in the tuple, so company2 simply becomes Settings. You only get an error where the code reads company2.name.
The same mistake can also compile without any error:
// User and Company share a shape, so swapping them type-checks
const [company3, user3] = await Promise.all([getUser("1"), getCompany("1")]);
If two requests return the same type, or both return any (which is what an untyped response.json() gives you), a reordered Promise.all compiles cleanly and runs with the wrong data.
Does Promise.all Preserve Order?
Yes. Promise.all preserves input order, so it is not at fault here. MDN states that the fulfilled array holds the values in the order of the promises passed, regardless of completion order. Index 0 belongs to the first input and index 1 to the second, even if the second promise settles first.
The Promise.all order guarantee is purely positional. Nothing links a result to the name you destructure it into. If the array of promises and the destructuring pattern stop matching, the method still does its job and your variables get the wrong values.
Results do get scrambled in one other case: a hand-written Promise.all that calls push() on each result as it arrives. That version returns values in completion order. The native method avoids this by writing each result to the index of its input.
Fix It Today With a Typed allKeyed Helper
The fix for mixed-up Promise.all results is to pass an object of promises instead of an array. Each result then comes back under its own name, so adding, removing or reordering a request cannot move a value into the wrong variable.
type Resolved<T> = { [K in keyof T]: Awaited<T[K]> };
export async function allKeyed<T extends Record<string, Promise<unknown>>>(
obj: T,
): Promise<{ [K in keyof T]: Awaited<T[K]> }> {
const entries = Object.entries(obj);
const values = await Promise.all(entries.map(([, promise]) => promise));
return Object.fromEntries(
entries.map(([key], i) => [key, values[i]]),
) as unknown as Resolved<T>;
}
const { user, company, settings } = await allKeyed({
user: getUser("1"),
settings: getSettings("1"),
company: getCompany("1"),
});
The keys and the promises both come from a single Object.entries call. The helper then matches each value back to its key by index in that same array, so the order in which the object lists its keys cannot cause a mismatch. The double assertion is there because Object.fromEntries returns a string-indexed record, and TypeScript cannot work out the per-key types from it. Each destructured variable is still inferred correctly (User, Company, Settings).
Two constraints apply. Object.fromEntries requires es2019 or later in your tsconfig lib. Object.entries skips symbol-keyed properties, so this helper ignores them.
How Do You Get Keyed Results From Promise.allSettled?
To get every outcome instead of failing fast, use the same pattern with Promise.allSettled. Each key then maps to a PromiseSettledResult:
export async function allSettledKeyed<T extends Record<string, Promise<unknown>>>(
obj: T,
): Promise<{ [K in keyof T]: PromiseSettledResult<Awaited<T[K]>> }> {
const entries = Object.entries(obj);
const results = await Promise.allSettled(entries.map(([, promise]) => promise));
return Object.fromEntries(
entries.map(([key], i) => [key, results[i]]),
) as unknown as { [K in keyof T]: PromiseSettledResult<Awaited<T[K]>> };
}
const results = await allSettledKeyed({ user: getUser("1"), company: getCompany("1") });
if (results.company.status === "fulfilled") {
console.log(results.company.value.name);
} else {
console.error(results.company.reason);
}
Checking status narrows the result, so value is available on fulfilled results and reason on rejected ones. This helper needs es2020 in lib.
What Are Promise.allKeyed and Promise.allSettledKeyed?
The TC39 Await Dictionary proposal adds Promise.allKeyed and Promise.allSettledKeyed to the language. It is at Stage 3, which means the design is close to final and engines can implement it. Firefox 155 added both methods. Other browsers and runtimes still need a polyfill.
With core-js, version 3.50.0 or later provides the polyfill, and the changelog lists a fix for sync promises in 3.51.0. The core-js Await Dictionary docs list the entry points:
import "core-js/actual/promise/all-keyed";
// or load both methods: import "core-js/proposals/await-dictionary";
const { user, settings, company } = await Promise.allKeyed({
user: getUser("1"),
settings: getSettings("1"),
company: getCompany("1"),
});
The es-shims alternative is promise.allkeyed. Install it with npm i promise.allkeyed, then call require('promise.allkeyed/shim')().
The proposal differs from the userland helper in two ways. It uses all own enumerable keys, including symbols, while Object.entries helpers skip symbols. It also fulfills with a null-prototype object, while Object.fromEntries returns an ordinary object.
| Approach | Matched by | Survives reordering | Symbol keys | Available |
|---|---|---|---|---|
Promise.all + array destructuring | Position | No | n/a | Everywhere |
Userland allKeyed | Key | Yes | No | Everywhere (lib es2019+) |
Promise.allKeyed | Key | Yes | Yes | Firefox 155+; polyfill elsewhere |
Rejections Still Fail Fast
The allKeyed and allSettledKeyed helpers above are thin wrappers, so they behave exactly like the methods they call. Promise.all rejects with the first rejection reason it sees, ignores any later rejections, and does not cancel the operations that are still running. Later rejections do not fire unhandledrejection, because Promise.all attaches handlers to every input. Promise.allKeyed also rejects with the first rejection reason.
If a fetcher can throw synchronously before it returns a promise, wrap it in Promise.try so the throw becomes a rejection. If the whole call has no handler, you end up with an Uncaught (in promise) TypeError.
Conclusion
Promise.all returns results in input order. The mismatch is between your array of promises and your destructuring pattern. Replace positional destructuring in your data loaders with the typed allKeyed helper now, and switch to Promise.allKeyed once your target engines ship it or your polyfill covers them. To see how other languages handle concurrent awaits, read OpenReplay’s comparison of async/await in JavaScript vs Rust vs Python.
FAQs
Does Promise.all keep the order of results when used with Array.map?
Yes. Promise.all(items.map(fetchItem)) returns results in the same order as items, because each result is stored at the index of its input promise. It does not matter which request finishes first. Non-promise values in the array are passed through and keep their position too. Order only breaks if a custom helper pushes results as they arrive.
Does Promise.allKeyed return a plain object?
No. Promise.allKeyed fulfills with a null-prototype object that has the same keys as the input, in the same order. A null-prototype object inherits nothing from Object.prototype, so methods like hasOwnProperty and toString are missing. Use Object.hasOwn or the in operator instead. A userland helper built on Object.fromEntries returns an ordinary object with the usual prototype.
Does Promise.allKeyed await promises inside nested objects?
No. Promise.allKeyed only processes the own enumerable properties of the object you pass in. A nested object counts as a single value and comes back as-is, so any promises inside it are still pending in the result. To await nested groups, call Promise.allKeyed on each inner object and pass the promises it returns as properties of the outer object.
How do I get keyed results while limiting concurrency?
Neither Promise.all nor Promise.allKeyed can limit concurrency. They only wait for promises that have already started. The p-map library has pMapKeyed and pMapSettledKeyed, which take an object or a Map plus a mapper function and a concurrency option. Like Promise.allKeyed, they return a null-prototype object with the same keys and include symbol keys. They also work in engines that don't ship the proposal yet.
Complete picture for complete understanding
Capture every clue your frontend is leaving so you can instantly get to the root cause of any issue with OpenReplay — the open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data.
Star on GitHub12k