Add a timeout to a promise

“Don’t keep me waiting”, a Black belt challenge from the CurlyScript Dojo. It uses what Freshman Year: Asynchronous JavaScript: Waiting Without Freezing teaches, and 2 tests check your answer.

The challenge

Write withTimeout(promise, ms) that resolves with the promise’s value if it finishes within ms milliseconds, or rejects with new Error("Timed out") if it takes longer. The wait(ms, value) helper is there to help you test.

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • withTimeout(wait(30, "fast"), 200) gives "fast"
  • withTimeout(wait(300, "slow"), 50).catch((e) => e.message) gives "Timed out"

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

Promise.race([a, b]) settles as soon as the first one does.

Hint 2

Make a second promise that rejects after ms, and race them.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

function withTimeout(promise, ms) {
  const timer = new Promise((_, reject) => {
    setTimeout(() => reject(new Error("Timed out")), ms);
  });
  return Promise.race([promise, timer]);
}

Learn what you need

This exercise uses what Freshman Year: Asynchronous JavaScript: Waiting Without Freezing teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning