How to Chain Promises in JavaScript: Simple Guide
You chain promises in JavaScript by returning a new
Promise or value inside a .then() callback, which passes its result to the next .then(). This creates a sequence where each step waits for the previous one to finish before running.Syntax
Promise chaining uses the .then() method to run asynchronous tasks one after another. Each .then() receives the result of the previous promise and returns a new value or promise.
promise.then(result => { ... }): handles the resolved value.- Return a value or another promise inside
.then()to pass it to the next step. - Use
.catch()at the end to handle errors from any step.
javascript
somePromise()
.then(result => {
// process result
return nextPromise(result);
})
.then(nextResult => {
// process nextResult
})
.catch(error => {
// handle any error
});Example
This example shows chaining three promises that add numbers step-by-step. Each step waits for the previous to finish and passes its result forward.
javascript
function addAsync(x, y) { return new Promise(resolve => { setTimeout(() => resolve(x + y), 500); }); } addAsync(1, 2) .then(sum1 => { console.log('First sum:', sum1); return addAsync(sum1, 3); }) .then(sum2 => { console.log('Second sum:', sum2); return addAsync(sum2, 4); }) .then(sum3 => { console.log('Third sum:', sum3); }) .catch(error => { console.error('Error:', error); });
Output
First sum: 3
Second sum: 6
Third sum: 10
Common Pitfalls
Common mistakes when chaining promises include:
- Not returning a promise or value inside
.then(), which breaks the chain. - Forgetting to handle errors with
.catch(), causing unhandled rejections. - Mixing callbacks and promises, which can cause confusing flow.
Always return a value or promise in .then() to keep the chain working.
javascript
/* Wrong: missing return breaks chain */ somePromise() .then(result => { doSomething(result); // no return here }) .then(nextResult => { // nextResult is undefined }); /* Right: return value or promise */ somePromise() .then(result => { return doSomething(result); }) .then(nextResult => { // nextResult is valid });
Quick Reference
Tips for chaining promises:
- Always return inside
.then()to pass results forward. - Use
.catch()once at the end to handle all errors. - Chain as many
.then()calls as needed for sequential async steps. - Remember that each
.then()gets the resolved value from the previous step.
Key Takeaways
Chain promises by returning a value or promise inside each .then() callback.
Use .catch() at the end to handle errors from any step in the chain.
Each .then() receives the resolved value from the previous promise.
Not returning inside .then() breaks the chain and causes undefined results.
Promise chaining helps run asynchronous tasks in a clear, sequential order.