AniUI Academy

Fall back when a request is too slow

easyAsync & Promises+150 XPPractice

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 value is too slow or rejects.
msnumber
How long to wait for value before 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 time

Fast 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 first

Too 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 fallback

A 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 fallback when ms elapses first.
  • Resolve with fallback when 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 — one Promise.race handles both branches.
  • The returned promise never rejects, so callers never need a try/catch.

Stuck? The javascript course covers everything this challenge needs.

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

Discussion

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

No comments yet. Be the first to say something.