Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Promise.all for an object of promises in JavaScript

47 Combinators over an object, keys kept

fair

Promise.all takes an array and gives you an array, so callers destructure by position. Write allObject and settledObject that take an object of promises and give back an object with the same keys. Check what happens to key order, to a rejection, and to a key that resolves to undefined.

Stuck? Three hints, smallest first
  1. 1. Take Object.keys once and reuse that array for both the values and the rebuild.
  2. 2. Object.fromEntries pairs the keys back up with the resolved values.
  3. 3. Key order comes from the object, not from which promise finished first.

The answer

const finishing = [];
const slow = (name, value, rounds) => (async () => {
  for (let i = 0; i < rounds; i++) await Promise.resolve();
  finishing.push(name);
  return value;
})();

async function allObject(tasks) {
  const keys = Object.keys(tasks);
  const values = await Promise.all(keys.map((key) => tasks[key]));
  return Object.fromEntries(keys.map((key, i) => [key, values[i]]));
}

async function settledObject(tasks) {
  const keys = Object.keys(tasks);
  const settled = await Promise.allSettled(keys.map((key) => tasks[key]));
  return Object.fromEntries(keys.map((key, i) => [
    key,
    settled[i].status === 'fulfilled'
      ? { ok: true, value: settled[i].value }
      : { ok: false, reason: settled[i].reason.message },
  ]));
}

const dashboard = await allObject({
  balance: slow('balance', 24000, 6),
  tills: slow('tills', 3, 2),
  area: 'lekki',                                  // a plain value passes through
});

const rejected = await allObject({
  balance: Promise.resolve(24000),
  tills: Promise.reject(new Error('till service offline')),
}).then(() => 'resolved', (err) => err.message);

const report = await settledObject({
  balance: Promise.resolve(24000),
  tills: Promise.reject(new Error('till service offline')),
});

const empty = await allObject({});
const missing = await allObject({ note: Promise.resolve(undefined) });
const withSymbol = await allObject({ [Symbol('hidden')]: Promise.resolve('dropped'), kept: Promise.resolve(1) });

console.log('dashboard :', dashboard);
console.log('finished in this order:', finishing);
console.log('rejected  :', rejected);
console.log('report    :', report);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('every key comes back with its resolved value', dashboard, { balance: 24000, tills: 3, area: 'lekki' });
test('the tills promise finished first, but the key order is the object\'s', [finishing, Object.keys(dashboard)], [['tills', 'balance'], ['balance', 'tills', 'area']]);
test('one rejection rejects the lot, exactly like Promise.all', rejected, 'till service offline');
test('while the settled version reports each key on its own', report, { balance: { ok: true, value: 24000 }, tills: { ok: false, reason: 'till service offline' } });
test('an empty object resolves to an empty object', [empty, Object.keys(empty)], [{}, []]);
test('a key that resolves to undefined is present but invisible to JSON', [Object.keys(missing), missing.note === undefined, JSON.stringify(missing)], [['note'], true, '{}']);
test('symbol keys are dropped, because Object.keys does not see them', Object.keys(withSymbol), ['kept']);
test('and the value under the surviving key is intact', withSymbol.kept, 1);

The array form makes callers count. const [balance, tills, area] = await Promise.all([...]) is fine with three entries and a liability with eight — insert a task in the middle and every name after it silently shifts by one. Naming the tasks removes the positional coupling entirely, and it reads better at the call site too.

Key order is worth being precise about. It is the object's own insertion order, fixed when Object.keys runs, and completely unrelated to which promise settled first — the second assertion shows tills finishing before balance and the result still reading balance, tills, area. That determinism is the reason this shape is safe to snapshot in a test.

The undefined assertion is a JSON trap rather than a promise one, and it catches people out precisely here, in code that builds a response object. The key exists, Object.keys reports it, and JSON.stringify drops it, so a client sees no field at all rather than a null. If the distinction between "missing" and "empty" matters to the consumer, map undefined to null before serialising.

Rejection behaviour is inherited, not designed: allObject rejects on the first failure and loses the successes, because Promise.all does. settledObject is the version to reach for when the keys are independent — a dashboard where a broken till service should still let you see the balance.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.