JavaScript Promise Chaining Last Updated : 18 Dec, 2024 Comments Improve Suggest changes Like Article Like Report Promise chaining allows you to execute a series of asynchronous operations in sequence. It is a powerful feature of JavaScript promises that helps you manage multiple operations, making your code more readable and easier to maintain.Allows multiple asynchronous operations to run in sequence.Reduces callback hell by eliminating deeply nested functions.Each then() returns a new promise, allowing further chaining.Error handling is easier with a single .catch() for the entire chain. JavaScript function task(message, delay) { return new Promise((resolve) => { setTimeout(() => { console.log(message); resolve(); }, delay); }); } // Chaining promises task('Task 1 completed', 1000) .then(() => task('Task 2 completed', 2000)) .then(() => task('Task 3 completed', 1000)); Output:Task 1 completedTask 2 completedTask 3 completedIn this example:task() is a function that returns a promise, simulating a delay using setTimeout.Each task waits for the previous one to complete before executing, thanks to the .then() chaining.The tasks will execute in order, printing:"Task 1 completed""Task 2 completed""Task 3 completed"This is the core of promise chaining, where each promise is linked to the next one through .then()Promise StatesA promise in JavaScript can be in one of three states, which determine how it behaves:Pending: This state represents the initial state of the promise. It is neither fulfilled nor rejected.Fulfilled: This state represents that the asynchronous operation has successfully completed, and the promise has resolved with a value.Rejected: This state represents that the asynchronous operation has failed, and the promise has rejected with a reason (error).Error Handling in Chaining JavaScript Promise.resolve(5) .then((num) => { console.log(`Value: ${num}`); throw new Error("Something went wrong!"); }) .then((num) => { console.log(`This won't run`); }) .catch((error) => { console.error(`Error: ${error.message}`); }); Output:Value: 5Error: Something went wrong!Chaining with Dependent Tasks JavaScript function fetchUser(userId) { return Promise.resolve({ id: userId, name: "GFG" }); } function fetchOrders(user) { return Promise.resolve([{ orderId: 1, userId: user.id }]); } fetchUser(101) .then((user) => { console.log(`User: ${user.name}`); return fetchOrders(user); }) .then((orders) => { console.log(`Orders: ${orders.length}`); }) .catch((error) => console.error(error)); Output:User: GFGOrders: 1Advanced Usage: Parallel and Sequential Tasks in a ChainYou can combine Promise.all() with chaining for efficient execution. JavaScript Promise.all([ Promise.resolve("Task 1 done"), Promise.resolve("Task 2 done") ]) .then(([result1, result2]) => { console.log(result1, result2); return Promise.resolve("Final Task done"); }) .then((finalResult) => console.log(finalResult)) .catch((error) => console.error(error)); Output:Task 1 done Task 2 doneFinal Task doneWhy Use Promise Chaining?Improved Readability: Makes code cleaner and easier to understand compared to deeply nested callbacks.Error Handling: Centralized error management with a single .catch() for the entire chain.Sequential Execution: Ensures tasks are executed one after the other, passing results along.Simplifies Dependencies: Handles tasks that depend on the output of previous asynchronous operations.Enhanced Debugging: Stack traces in Promise chains are easier to follow compared to callback chains.When to Use Promise Chaining?Dependent Async Operations: When one async task relies on the result of another (e.g., fetching user data, then their orders).Sequential Steps: For workflows with multiple stages, like data transformation or processing pipelines.Avoiding Callback Hell: To keep the structure of async code flat and maintainable.Error Propagation: When you need to ensure that an error in any step is caught and handled.Data Aggregation: Combining results from multiple async calls in sequence.Cleanup After Tasks: Using .finally() to execute code regardless of success or failure. Comment More infoAdvertise with us Next Article JavaScript Promise Chaining amansingla Follow Improve Article Tags : JavaScript Web Technologies javascript-basics Similar Reads JavaScript Promise JavaScript Promises make handling asynchronous operations like API calls, file loading, or time delays easier. Think of a Promise as a placeholder for a value that will be available in the future. It can be in one of three statesPending: The task is in the initial state.Fulfilled: The task was compl 4 min read Promise vs Callback in JavaScript In JavaScript, managing asynchronous operations is a key aspect of modern web development. Two popular approaches for handling these operations are Promises and Callbacks. While both techniques are designed to deal with tasks that take time to complete (like fetching data from a server), they work d 5 min read NodeJS Promise Chaining Node.js is great at handling tasks that don't need to happen instantly, like fetching data from a website. Promise chaining helps you manage these tasks in a specific order, one after the other.What is Promise Chaining? Promise chaining in Node.js allows you to execute multiple asynchronous operatio 4 min read JavaScript Promise any() Method JavaScript Promise any() method is a static method that takes an array of promises as a parameter and returns the first fulfilled promise. It returns a rejected value when all of the promises in the array return rejects or if the array is empty. When all the promises are rejected an AggregateError i 2 min read JavaScript Promise constructor JavaScript Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code. Promise constructor in JavaScript is mainly used to wrap functions that do n 2 min read JavaScript Promise catch() Method JavaScript Promise catch() method is called whenever a promise is rejected. This method itself returns a promise so it can also be used to chain promises. This method is used for error handling. This method is mainly used after .then to chain a promise and handle reject condition. This method intern 2 min read JavaScript Promise all() Method The Promise.all() method in JavaScript is used for handling multiple asynchronous operations simultaneously. It takes an array (or any iterable) of promises and returns a single promise that resolves when all the input promises resolve or reject if any one of the promises fails. This makes it ideal 6 min read JavaScript Promise finally() Method The finally() method of the Promise object is used to return a callback when a Promise is settled (either fulfilled or rejected).Syntax:task.finally(onFinally() { });Parameters: This method has a single parameter as mentioned above and described below:onFinally: It is the function that will be calle 1 min read How to Implement a Custom Promise in JavaScript ? A custom Promise in JavaScript encapsulates asynchronous operations. It takes two parameters, resolves and rejects functions, and executes an async task. Resolve is called on success with the result, while reject is called on failure with an error. Table of Content Using Class SyntaxUsing Factory Fu 3 min read JavaScript - How to Handle Errors in Promise.all? To handle errors in Promise.all(), you need to understand that it fails immediately if any of the promises reject, discarding all resolved values. This behavior can lead to incomplete operations and potential application crashes. The best way to manage errors in Promise.all() is by using .catch() in 3 min read Like