SyntaxStudy
Sign Up
JavaScript Beginner 4 min read

Promise Chaining

Chaining .then()

Each .then() returns a new Promise. Returning a value passes it to the next .then(); returning a Promise chains asynchronously.

Example
fetch("/api/user/1")
  .then(res => res.json())
  .then(user => fetch(`/api/posts?userId=${user.id}`))
  .then(res => res.json())
  .then(posts => render(posts))
  .catch(err => showError(err));
Pro Tip

A single .catch() at the end catches errors from any step in the chain.