then()
ES6+Attaches callbacks for the resolution and/or rejection of the Promise.
Syntax
promise.then(onFulfilled, onRejected)Parameters
onFulfilled Function A function called when the Promise is fulfilled
onRejected Function optionalA function called when the Promise is rejected
Return Value
A new Promise that resolves to the return value of the callback
Examples
const promise = Promise.resolve(42);
promise.then(value => {
console.log(value);
}); 📌 When to Use
Use then() to handle successful async operations, transform data through chaining, or sequence multiple async operations.
⚠️ Common Mistakes
Forgetting to return values in then() chains, breaking the chain with undefined.
Not handling rejections - unhandled promise rejections can crash Node.js applications.
Creating unnecessary nesting instead of chaining - leads to callback hell.
✅ Best Practices
Use async/await for cleaner code, but understand then() for legacy codebases.
Always end chains with catch() or use the second argument of then() sparingly.
⚡ Performance Notes
Each then() creates a new Promise object. For high-performance scenarios, minimize chain length. Consider batching with Promise.all() for parallel operations.
🌍 Real World Example
API Data Transformation Pipeline
Chain API calls and transform data through multiple processing stages.
function fetchUserWithPosts(userId) {
return fetch(`/api/users/${userId}`)
.then(response => {
if (!response.ok) throw new Error('User not found');
return response.json();
})
.then(user => {
return fetch(`/api/users/${userId}/posts`)
.then(res => res.json())
.then(posts => ({ ...user, posts }));
})
.then(userWithPosts => {
// Transform data
return {
...userWithPosts,
postCount: userWithPosts.posts.length,
recentPost: userWithPosts.posts[0] || null
};
});
}
fetchUserWithPosts(1).then(console.log).catch(console.error);