LearnFrenzy
Sign in Take a free test

Promises · Promises Coding Problems · Question 3

Add a timeout to any promise in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
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
main.js
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));

Output Verified by running it on Node.js

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links