Return a promise that resolves after a delay

“Patient adder”, 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 slowAdd(a, b, ms) that returns a promise which resolves to a + b after ms milliseconds.

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

  • SlowAdd(2, 3, 50) resolves to 5: slowAdd(2, 3, 50) gives 5
  • It really waits: (async () => { const start = Date.now(); await slowAdd(1, 1, 120); return Date.now() - start >= 100; })() gives true

Hints

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

Hint 1

return new Promise((resolve) => setTimeout(() => resolve(…), ms));

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
function slowAdd(a, b, ms) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(a + b), ms);
  });
}

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