Question 3
Back to Exercise
Write withTimeout(promise, ms) that rejects with a TimeoutError if the promise has not settled within ms, and test it with a fast and a slow request.
Solution
function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(Object.assign(new Error(`timed out after ${ms} ms`), { name: "TimeoutError" })), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
const request = (ms, data) => new Promise((r) => setTimeout(() => r(data), ms));
withTimeout(request(5, "fast data"), 20).then(console.log, (e) => console.log(e.name, e.message));
withTimeout(request(50, "slow data"), 20).then(console.log, (e) => console.log(e.name, e.message));
fast data TimeoutError timed out after 20 ms
race settles with whichever promise settles first. finally clears the timer so a fast response does not leave a pending timeout behind.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!