Async & Promiseseasy

Missing return in .then() chain

Identify the common bug where a promise is created inside `.then` but not returned, breaking chaining and error propagation.

Asked at Google, Netflix, Uber

#promises#then#pitfalls#error handling

Answer

// Buggy:
fetchUser()
  .then((user) => {
    fetchOrders(user.id) // missing return
  })
  .then((orders) => {
    console.log(orders) // often undefined
  })

// Correct:
fetchUser()
  .then((user) => {
    return fetchOrders(user.id)
  })
  .then((orders) => {
    console.log(orders)
  })
  .catch(console.error)

// Async/await equivalent (usually clearer):
async function run() {
  const user = await fetchUser()
  const orders = await fetchOrders(user.id)
  console.log(orders)
}

Practise more Async & Promises questions →