AniUI Academy

Give a promise a deadline

mediumAsync & Promises+250 XPPractice

Networks do not always fail loudly — sometimes a request simply never answers. Without a deadline your loading state is permanent, which is a worse experience than an honest error.

Implement withTimeout(value, ms, message). It returns a promise that fulfils with the resolved value of value if it settles within ms milliseconds, and rejects with that input's reason if the input rejects first. If neither happens within ms, reject with a new Error(message). When message is not supplied, use exactly "Timed out". A non-promise value counts as already fulfilled. Falsy values such as 0 must resolve normally rather than being treated as missing.

Arguments

valuePromise<T> | T
The input promise or value to race against the clock.
msnumber
Milliseconds to wait before rejecting with a timeout error.
messagestring
The timeout error message. Defaults to "Timed out".

Returns

Promise<T> — A promise that resolves with the input's value when it settles in time, rejects with the input's reason, or rejects with a timeout Error once ms has elapsed.

Examples

const data = await withTimeout(
  new Promise((resolve) => setTimeout(() => resolve("data"), 5)),
  200
);
// data === "data" — arrived in time

Fast enough: the input value passes through.

try {
  await withTimeout(
    new Promise((resolve) => setTimeout(() => resolve("late"), 400)),
    20,
    "too slow"
  );
} catch (error) {
  // error.message === "too slow"
}

Too slow: rejects with your message.

const result = await withTimeout(Promise.resolve(0), 100);
// result === 0 — falsy values still resolve normally

0, empty string, null all resolve rather than being treated as missing.

What it has to do

  • Fulfil with the input's value when it settles in time, including falsy values.
  • Reject with an Error carrying message once ms has elapsed.
  • Default the timeout message to Timed out.
  • Pass an input rejection straight through as the rejection reason.
  • Clear the pending timer once the input settles.

Notes

  • Clear the pending timer in both the fulfil and reject handlers — otherwise it fires after the input has already settled.
  • An input rejection passes straight through; the timeout error only wins if the input hasn't settled by ms.
Asked atGoogleStripe

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.