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:
- A value is returned, which is passed down to the next
.then()
in the chain. - 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:
-
Initial Promise: The first promise resolves with the value
1
. -
First
.then()
Block: The first.then()
receives the value1
, logs it, and returns1 * 2
(which is2
). -
Second
.then()
Block: The second.then()
receives the value2
, logs it, and returns2 * 3
(which is6
). -
Third
.then()
Block: The third.then()
receives the value6
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
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/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.