All posts

Promises (part two): the legend of the lost Promise

📅 Created 6 years ago → updated after 6 years

🏷️ #js #async #promises #archive

🔗 Async Javascript: tricks with Promises (part one)

If the function in .then() is synchronous, the following .then() is invoked instantly:

Promise.resolve(5)
   :
   : ⌛ async
   :
  .then(x => x + 1)
   |
   | right away
   |
  .then(x => console.log(x))    // 6

But if the function in .then() returns a Promise(), following .then() handler is invoked after that Promise is resolved:

Promise.resolve(5)
   :
   : ⌛ async
   :
  .then(x => {
      return Promise.resolve(x + 1)
  })
   :
   : ⌛ async
   :
  .then(x => console.log(x))    // 6

The crucial point here: the Promise() inside .then() must be returned! Otherwise following happens:

Promise.resolve(5)
   :
   : ⌛ async
   :
  .then(x => {
      Promise.resolve(x + 1)
  })                :
   |                :
   | right away     :........ resolved into nowhere
   |
  .then(x => console.log(x))    // ❗ undefined

Why the terminal .then() shows undefined? That's easy: it was invoked with what the preceding .then() returned. It was undefined as the Promise inside there was invoked but not returned.

Hope this helps spending evenings debugging lost error messages 🙂

Array methods (JS/TS) Async Javascript: tricks with Promises (part one)