Sequential Async Operations
What you'll learn: How to use chained .then() calls to perform asynchronous operations one after another in a guaranteed order.
The Core Idea
When you need multiple async operations to happen in sequence — where each step must complete before the next begins — promise chaining is your solution. By returning a promise from one .then() handler, you ensure the next .then() waits for that promise to settle before executing.
Think of it like a relay race: each runner (async operation) must complete their leg and hand off the baton before the next runner can start. The chain ensures proper order.
How It Works
Each .then() that returns a promise causes the chain to pause until that promise resolves:
fetchUser(userId)
.then(user => {
// First operation completes, return next promise
return fetchUserPosts(user.id);
})
.then(posts => {
// Second operation completes, return next promise
return fetchPostComments(posts[0].id);
})
.then(comments => {
// Third operation completes
console.log('Comments:', comments);
})
.catch(error => {
console.error('Failed at some step:', error);
});
Each step waits for the previous promise to resolve. If fetchUserPosts takes 2 seconds, fetchPostComments won't even start until those 2 seconds are up.
Why This Matters
Sequential operations are essential when later steps depend on earlier results. You can't fetch post comments without first knowing which post ID to use. Promise chains give you this dependency management naturally, without the rightward drift of nested callbacks.
Key Takeaway: Returning promises from .then() handlers creates sequential async flows where each operation waits for the previous one to complete, maintaining clear order and avoiding callback hell.