Understanding Promises | Javascript - 1

Deepak Kumar - Aug 28 - - Dev Community

Promise chaining is a powerful feature in JavaScript that allows you to sequence multiple asynchronous operations in a clean and readable way by chaining .then() methods. Instead of nesting callbacks inside one another (known as "callback hell"), promise chaining enables a more linear flow of operations, making code easier to manage.

How Promise Chaining Works

When you call the .then() method on a promise, it returns a new promise. You can chain multiple .then() methods, where the result of one .then() is passed as an input to the next one in the chain. This chaining continues until either:

  1. A value is returned, which is passed down to the next .then() in the chain.
  2. An error is thrown or a rejected promise is returned, which breaks the chain and skips all subsequent .then() blocks, going directly to the nearest .catch() block.

Each .then() in the chain handles the result from the previous operation, making it easy to handle asynchronous tasks sequentially.

Basic Example:

const promiseChain = new Promise((resolve, reject) => {
  resolve(1);  // Initial promise resolves with 1
});

promiseChain
  .then((result) => {
    console.log(result);  // 1
    return result * 2;    // Return 2 to the next .then() in the chain
  })
  .then((result) => {
    console.log(result);  // 2
    return result * 3;    // Return 6 to the next .then() in the chain
  })
  .then((result) => {
    console.log(result);  // 6
  })
  .catch((error) => {
    console.error(error); // Handle any error that occurs in the chain
  });
Enter fullscreen mode Exit fullscreen mode

How It Works:

  1. Initial Promise: The first promise resolves with the value 1.
  2. First .then() Block: The first .then() receives the value 1, logs it, and returns 1 * 2 (which is 2).
  3. Second .then() Block: The second .then() receives the value 2, logs it, and returns 2 * 3 (which is 6).
  4. Third .then() Block: The third .then() receives the value 6 and logs it.

If any of the .then() blocks had thrown an error or returned a rejected promise, the .catch() block would handle that error.

Key Points to Remember:

  • Each .then() method returns a new promise.
  • You can chain .then() methods to handle asynchronous operations sequentially.
  • If a promise in the chain is rejected, subsequent .then() blocks are skipped, and the error is passed to the nearest .catch() block.
  • You can return another promise inside a .then() block, creating nested chains, but the code will remain clean and readable.

Example with a Real-world Use Case:

Let's say you need to fetch some user data from an API, then fetch that user's posts, and finally log them.

fetch('https://api.example.com/user')
  .then((response) => response.json())
  .then((user) => {
    console.log(user); // Logs user data
    return fetch(`https://api.example.com/user/${user.id}/posts`);
  })
  .then((response) => response.json())
  .then((posts) => {
    console.log(posts); // Logs user's posts
  })
  .catch((error) => {
    console.error('Error:', error);
  });
Enter fullscreen mode Exit fullscreen mode

In this example:

  • The first fetch gets the user data.
  • The second fetch gets the user's posts.
  • Any error during the fetch operations will be caught and logged by .catch().

Promise chaining simplifies handling such sequential asynchronous operations.

.
Terabox Video Player