AniUI Academy

Try each source until one works

mediumAsync & Promises+250 XPPractice

Reading a setting might mean trying an in-memory value, then a local snapshot, then the network. Each attempt is a different function, they must be tried in order, and the expensive ones must not run if an earlier one succeeds.

Implement firstSuccessful(tasks), where tasks is an array of zero-argument functions returning promises. Call them one at a time in order and resolve with the result of the first that fulfils, without calling the remaining tasks. If a task rejects, move on to the next one. If every task rejects, reject with the error from the last task. If tasks is empty, reject with new Error("No tasks provided").

Arguments

tasksArray<() => Promise<T>>
Zero-argument functions returning promises, tried in order.

Returns

Promise<T> — Resolves with the first fulfilled value. Rejects with the last task's error if all fail, or Error("No tasks provided") for an empty list.

Examples

const tried = [];
const value = await firstSuccessful([
  async () => { tried.push("cache"); throw new Error("empty"); },
  async () => { tried.push("edge"); throw new Error("miss"); },
  async () => { tried.push("origin"); return "fresh"; },
]);
// value === "fresh", tried === ["cache", "edge", "origin"]

Cache-first fallbacks without nesting try/catch.

try {
  await firstSuccessful([]);
} catch (error) {
  // error.message === "No tasks provided"
}

An empty list rejects with a sentinel error, not silently.

What it has to do

  • Call the tasks one at a time, in order.
  • Resolve with the first fulfilled value and skip the remaining tasks.
  • Continue past a rejecting task.
  • Reject with the last task's error when they all reject.
  • Reject with an Error reading No tasks provided for an empty array.

Notes

  • Call tasks one at a time with await inside try/catch — don't start them all up front, that defeats the point of trying expensive ones last.
  • An empty array rejects with a sentinel Error, not silently resolves — callers should always handle the no-tasks case explicitly.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 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.