Ask any question about JavaScript here... and get an instant response.
How can I chain multiple promises to execute sequentially in JavaScript?
Asked on Oct 15, 2025
Answer
To chain multiple promises in JavaScript and execute them sequentially, you can use the "then" method. Each "then" returns a new promise, allowing you to chain further operations.
<!-- BEGIN COPY / PASTE -->
function firstTask() {
return new Promise((resolve) => {
setTimeout(() => {
console.log("First task completed");
resolve("Result of first task");
}, 1000);
});
}
function secondTask(resultFromFirst) {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Second task completed with:", resultFromFirst);
resolve("Result of second task");
}, 1000);
});
}
function thirdTask(resultFromSecond) {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Third task completed with:", resultFromSecond);
resolve("Result of third task");
}, 1000);
});
}
firstTask()
.then(secondTask)
.then(thirdTask)
.then((finalResult) => {
console.log("All tasks completed with:", finalResult);
})
.catch((error) => {
console.error("An error occurred:", error);
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- This example demonstrates chaining three promises to execute sequentially.
- Each function returns a promise that resolves after a delay, simulating asynchronous operations.
- The "then" method is used to pass the result of each promise to the next function in the chain.
- The "catch" method handles any errors that occur in the promise chain.
Recommended Links:
