Try each source until one works
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
ErrorreadingNo tasks providedfor an empty array.
Notes
- Call tasks one at a time with
awaitinside 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.
- 1.returns the first success without running later tasks
- 2.skips past failing tasks
- 3.rejects with the last error when all tasks fail
- 4.rejects for an empty task list
- 5.never runs two tasks at once
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.