Avoiding Accidental Promise Creation
You'll learn how to spot and eliminate unnecessary promises that sneak into your chains, making your code cleaner and more efficient.
The Problem
When working with promise chains, it's easy to accidentally wrap values in extra promises without realizing it. This happens most often when you return a value from .then() that already is a promise, or when you create a new promise unnecessarily.
Common Accidental Patterns
Wrapping a Promise in a Promise
fetch('/api/user')
.then(response => {
// ❌ Accidental extra promise
return Promise.resolve(response.json());
})
.then(data => console.log(data));
Here, response.json() already returns a promise. Wrapping it in Promise.resolve() creates an unnecessary extra layer. The fix:
fetch('/api/user')
.then(response => response.json()) // ✅ Just return the promise
.then(data => console.log(data));
The Promise Constructor When You Don't Need It
function getUser(id) {
// ❌ Unnecessary promise wrapper
return new Promise((resolve, reject) => {
fetch(`/api/user/${id}`)
.then(response => resolve(response.json()))
.catch(err => reject(err));
});
}
Since fetch() already returns a promise, just return it directly:
function getUser(id) {
// ✅ Simpler and cleaner
return fetch(`/api/user/${id}`)
.then(response => response.json());
}
Think Like This
When something already gives you a promise, don't gift-wrap it again. Just pass it along. The chain will automatically unwrap it for you.
Key Takeaway: Returning a promise from .then() automatically integrates it into the chain—no need for Promise.resolve() or the constructor. Keep chains flat by recognizing when you already have a promise.