Overview
Wrap a timer in a Promise so other code can wait for its result with then, instead of nesting callbacks.
- new Promise((resolve) => ...)
- setTimeout inside a Promise
- then runs after the current code
Short Course
A Promise stands for a value that comes later: call resolve(value) when
it is ready, read it with .then. Trap: inside .then, forget return and
the next step receives undefined.
const ready = new Promise((resolve) => {
setTimeout(() => resolve(21), 100);
});
ready
.then((n) => n * 2) // return is implicit here
.then((n) => console.log(n)); // 42
Task
Write delay(value, ms) that returns a Promise resolving to value after ms
milliseconds, e.g. delay("done", 10) resolves to done.
Test Suites
Pending
Next
Output