Lesson 6 of 8
Request timeouts
- 13 min
- 5 checks
- 3 hints
- Go to task
Goal
Put a limit on the wait
Explanation
A request with no timeout can wait forever if the network is weak or the server is stuck, leaving the user staring at "Loading…" with no end in sight. It's better for the request to fail after a few seconds with a clear message, so the user knows to try again.
Promise.race returns the outcome of whichever promise settles first, whether it succeeds or fails. So make the request race against a promise that rejects when time is up: if the request finishes first, its result goes through, and if the timer wins, the race fails with the timeout error.
Keep in mind that a timeout ends your waiting, not the request itself. The request keeps running in the background until its response arrives, with nobody waiting for it anymore. Actually stopping it is the subject of the next lesson.
Your task
Write the function withTimeout(promise, ms). If the promise settles within ms milliseconds, pass its outcome through unchanged, whether that's a value or an error. Otherwise, reject with new Error('Request timed out').
Checks
5 checks- A fast request passes its value through
- A slow request is rejected when time runs out, not after it arrives
- The rejection carries an error that mentions the timeout
- The request's own error comes through unchanged
- The slow request button shows the timeout message