Hack Frontend Community

What is Promise Chaining in JavaScript

What is Promise Chaining?

Promise chaining is a mechanism where each .then() returns a new promise, allowing you to build a chain of asynchronous operations.

Essentially, this means that the result of one .then() is passed to the next .then() until the final result is reached.

Example

fetch("/user.json")
  .then(response => response.json())               // promise #1
  .then(user => fetch(`/users/${user.id}`))        // promise #2
  .then(response => response.json())               // promise #3
  .then(userData => console.log(userData))         // promise #4
  .catch(error => console.error(error));           // error handling

Here each .then() returns a new promise, and the next .then() waits for its completion — this is called promise chaining.

Important to Remember

  • Each .then() always returns a promise, even if return isn't explicitly specified.
  • If you return a value (not a promise) inside .then(), it will automatically be wrapped in a promise.
  • If an exception is thrown inside .then() — it will be passed to the nearest .catch().

Wrong Example (without chaining)

fetch("/user.json").then(response => {
  response.json().then(user => {
    fetch(`/users/${user.id}`).then(response => {
      response.json().then(userData => {
        console.log(userData);
      });
    });
  });
});

Such "nested" use of promises is called "callback hell" and makes code harder to read and maintain.

Same with Chaining

fetch("/user.json")
  .then(res => res.json())
  .then(user => fetch(`/users/${user.id}`))
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

Conclusion

  • Promise chaining is an important concept for working with asynchronous code.
  • Use .then() correctly: return promises to create chains.
  • This allows writing clean, linear and convenient code, without nesting and confusion.

Fact:

async/await is syntactic sugar over Promise chaining.