AniUI Academy

Implement Promise.allSettled from scratch

mediumAsync & Promises+250 XPPractice

When you save six form sections at once, Promise.all throws away five results the moment one fails. allSettled waits for all of them and describes each outcome so the UI can mark exactly which section needs attention.

Implement allSettled(promises) without using Promise.allSettled. It resolves with an array in input order, one entry per input. A fulfilled input produces an object with exactly two properties, status: "fulfilled" and value. A rejected input produces an object with exactly two properties, status: "rejected" and reason. Non-promise entries count as fulfilled. The returned promise never rejects, and an empty array resolves with an empty array.

Arguments

promisesArray<Promise | any>
An array of promises or plain values.

Returns

Promise<Array<{ status: 'fulfilled' | 'rejected', value?: any, reason?: any }>> — A promise that resolves with one descriptor per input, in input order. Never rejects.

Examples

const failing = Promise.reject("bad");
failing.catch(() => {});
const results = await allSettled([Promise.resolve(1), failing, 3]);
// results === [
//   { status: "fulfilled", value: 1 },
//   { status: "rejected", reason: "bad" },
//   { status: "fulfilled", value: 3 },
// ]

Each entry carries exactly status plus either value or reason.

What it has to do

  • Resolve with one entry per input, in input order.
  • Use exactly the keys status and value for a fulfilled entry.
  • Use exactly the keys status and reason for a rejected entry.
  • Never reject, even when every input rejects.
  • Resolve with [] for an empty array.

Notes

  • Map each input to a promise that can only fulfil: attach both handlers and return the descriptor object from each, then hand the array to Promise.all.
  • Unlike Promise.all, this never rejects — even when every input rejects.
Asked atGoogleAmazon

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
4 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.