Mixing Sync and Async in Chains
What you'll learn: How to seamlessly combine synchronous return values and asynchronous promises within the same promise chain.
The Core Idea
Promise chains are incredibly flexible—you don't have to return a promise from every .then() handler. You can mix synchronous return values and asynchronous promises freely, and JavaScript handles both gracefully. When you return a plain value, it's automatically wrapped in a resolved promise. When you return a promise, the chain waits for it to settle.
How It Works
Think of a promise chain like a production line where some stations do instant work (sync) and others need time (async). The line doesn't care which is which—it just moves the result forward appropriately.
fetch('/api/user')
.then(response => response.json()) // Returns a promise
.then(data => data.username) // Returns a string (sync)
.then(username => username.toUpperCase()) // Returns a string (sync)
.then(upperName => {
console.log(upperName);
return fetch(`/api/profile/${upperName}`); // Returns a promise
})
.then(response => response.json()) // Returns a promise
.then(profile => {
return profile.age * 2; // Returns a number (sync)
})
.then(doubledAge => {
console.log(doubledAge);
});
The chain flows smoothly whether you're transforming data synchronously (username.toUpperCase()) or performing another async operation (fetch()). Promise chains automatically "flatten" nested promises—you never get a Promise<Promise<T>>.
When to Mix Them
Use synchronous returns for simple data transformations (mapping, filtering, calculating). Use promise returns when you need another async operation (additional network calls, file reads, timers). This flexibility lets you keep chains readable without unnecessary promise wrapping.
Key Takeaway: Promise chains handle both synchronous values and asynchronous promises seamlessly—return what makes sense for each step, and the chain automatically wraps sync values in resolved promises while waiting for async promises to settle.