Fall back when a request is too slow
A widget that waits three seconds for fresh numbers feels broken. Showing slightly stale data after 300ms feels instant, and the fresh data can arrive later.
Implement withFallback(value, fallback, ms). It returns a promise that resolves with the resolved value of value if that happens within ms milliseconds. If ms elapses first, resolve with fallback. If value rejects before ms elapses, also resolve with fallback. A non-promise value is treated as already fulfilled. The returned promise must never reject.
Arguments
valuePromise<T> | T- The primary promise or value.
fallbackT- The value to use if
valueis too slow or rejects. msnumber- How long to wait for
valuebefore using the fallback.
Returns
Promise<T> — A promise that resolves with value's result if it arrives within ms, otherwise with fallback. Never rejects.
Examples
const live = new Promise((resolve) => setTimeout(() => resolve("live"), 5));
const result = await withFallback(live, "cached", 100);
// result === "live" — it arrived in timeFast enough: the fresh value wins.
const slow = new Promise((resolve) => setTimeout(() => resolve("live"), 400));
const result = await withFallback(slow, "cached", 30);
// result === "cached" — the timer fired firstToo slow: the fallback wins.
const failing = Promise.reject(new Error("offline"));
failing.catch(() => {});
const result = await withFallback(failing, "cached", 100);
// result === "cached" — rejection also triggers the fallbackA rejection is handled the same as a timeout.
What it has to do
- Resolve with the input's value when it fulfils within
ms. - Resolve with
fallbackwhenmselapses first. - Resolve with
fallbackwhen the input rejects. - Accept a plain value as well as a promise.
- Never reject.
Notes
- Race the input against a timer that resolves with the fallback, and
.catch()the input to the fallback as well — onePromise.racehandles both branches. - The returned promise never rejects, so callers never need a try/catch.
Stuck? The javascript course covers everything this challenge needs.
- 1.uses the live value when it arrives in time
- 2.uses the fallback when the value is too slow
- 3.uses the fallback when the value rejects
- 4.accepts a plain value
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.