Resolve an object of promises into an object of values
A dashboard page loads several independent pieces of data in parallel. With Promise.all the code ends up juggling array positions: const [user, stats, , flags] = await Promise.all([...]), and inserting a new request shifts every index. Naming each request is much clearer:
const { user, stats, flags } = await resolveRecord({
user: api.getUser(id),
stats: api.getStats(id),
flags: { darkMode: true }, // plain values are allowed too
});
Implement resolveRecord(record), which merges the results of every value in an object into a single object.
resolveRecord(record) // => Promise<object>
record is a plain object. Its values can be promises, other thenables (objects with a then method), or plain values.record, in the same order, each holding the value its promise fulfilled with (or the plain value itself). Key order must not depend on which value finishes first.{}.Error whose:
message is Failed to resolve "<key>", for example Failed to resolve "stats";key property is the failing key;cause property is the original rejection reason, unchanged.Later rejections are ignored.
record.Promise.all, Promise.allSettled, Promise.any or Promise.race.await resolveRecord({
user: Promise.resolve({ id: 7, name: 'Ana' }),
unread: 3,
theme: new Promise((resolve) => setTimeout(() => resolve('dark'), 10)),
});
// => { user: { id: 7, name: 'Ana' }, unread: 3, theme: 'dark' }
await resolveRecord({}); // => {}
try {
await resolveRecord({
user: Promise.resolve('Ana'),
stats: Promise.reject(new Error('503 Service Unavailable')),
never: new Promise(() => {}), // does not block the rejection
});
} catch (error) {
error.message; // => 'Failed to resolve "stats"'
error.key; // => 'stats'
error.cause.message; // => '503 Service Unavailable'
}