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.
It prints
What the tests check
- SlowAdd(2, 3, 50) resolves to 5:
slowAdd(2, 3, 50)gives5 - It really waits:
(async () => { const start = Date.now(); await slowAdd(1, 1, 120); return Date.now() - start >= 100; })()givestrue
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
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.