Give a promise a deadline
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 timeFast 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 normally0, 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
Errorcarryingmessageoncemshas 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.
Stuck? The javascript course covers everything this challenge needs.
- 1.resolves when the value arrives in time
- 2.rejects with an Error carrying the message
- 3.defaults the message to Timed out
- 4.passes an input rejection straight through
- 5.resolves a falsy value normally
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.