Understanding Promises | Javascript – 1

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”), promi…


This content originally appeared on DEV Community and was authored by Deepak Kumar

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
  });

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);
  });

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.


This content originally appeared on DEV Community and was authored by Deepak Kumar


Print Share Comment Cite Upload Translate Updates
APA

Deepak Kumar | Sciencx (2024-08-28T20:47:33+00:00) Understanding Promises | Javascript – 1. Retrieved from https://www.scien.cx/2024/08/28/understanding-promises-javascript-1/

MLA
" » Understanding Promises | Javascript – 1." Deepak Kumar | Sciencx - Wednesday August 28, 2024, https://www.scien.cx/2024/08/28/understanding-promises-javascript-1/
HARVARD
Deepak Kumar | Sciencx Wednesday August 28, 2024 » Understanding Promises | Javascript – 1., viewed ,<https://www.scien.cx/2024/08/28/understanding-promises-javascript-1/>
VANCOUVER
Deepak Kumar | Sciencx - » Understanding Promises | Javascript – 1. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/28/understanding-promises-javascript-1/
CHICAGO
" » Understanding Promises | Javascript – 1." Deepak Kumar | Sciencx - Accessed . https://www.scien.cx/2024/08/28/understanding-promises-javascript-1/
IEEE
" » Understanding Promises | Javascript – 1." Deepak Kumar | Sciencx [Online]. Available: https://www.scien.cx/2024/08/28/understanding-promises-javascript-1/. [Accessed: ]
rf:citation
» Understanding Promises | Javascript – 1 | Deepak Kumar | Sciencx | https://www.scien.cx/2024/08/28/understanding-promises-javascript-1/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.