Promises

Wrap a timer in a promise, then chain .then calls so each step starts when the previous one finishes.

JavaScript · beginner · 8 min · 18 steps · free

What you'll learn

Promises.js

function wait(ms, value) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value), ms);
  });
}

console.log('ordering coffee');
wait(300, 'coffee')
  .then((drink) => {
    console.log('got', drink);
    return wait(200, 'cake');
  })
  .then((food) => console.log('got', food));
console.log('waiting…');

Step by step

  1. Before the first line runs, JavaScript reads the whole file: the function wait already exists. This is called hoisting.
  2. It prints ordering coffee.
  3. wait(300, "coffee") starts a 300 ms wait and returns a promise for the result.
  4. new Promise runs this function at once, passing resolve: calling it later fulfils the promise.
  5. setTimeout hands the callback to a timer and returns at once. It will run after 300 ms, once the call stack is empty: see Timers waiting.
  6. The promise is still pending: the coffee is not ready.
  7. .then registers a callback and returns at once. JavaScript does not wait here: the callback runs later, when the promise settles.
  8. JavaScript does not wait: "waiting…" prints before the coffee arrives.
  9. 300 ms have passed and the call stack is empty, so the event loop runs the timer's callback. setTimeout callback gets no arguments and returns undefined.
  10. After 300 ms resolve("coffee") fulfils the promise, so the first .then callback runs with drink = "coffee".
  11. It prints got coffee.
  12. JavaScript calls wait(), with ms = 200 and value = "cake". It gets its own variables.
  13. JavaScript calls (resolve) => { setTimeout(() …, with resolve = a built-in function. It gets its own variables.
  14. setTimeout hands the callback to a timer and returns at once. It will run after 200 ms, once the call stack is empty: see Timers waiting.
  15. wait returns Promise { <pending> }.
  16. Returning a promise from .then makes the next .then wait for it: 200 ms more.
  17. 200 ms have passed and the call stack is empty, so the event loop runs the timer's callback. setTimeout callback gets no arguments and returns undefined.
  18. The cake arrives and the chain is done.

Common mistakes

Best practices

Key takeaways

Check yourself

new Promise runs its function?

Answer: Immediately

p.then returns?

Answer: A new promise

·

More in Asynchronous JavaScript