JavaScript Promises Deep Dive
Master asynchronous programming with promises.
Promise Basics
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) resolve("Done!");
else reject(new Error("Failed!"));
});
promise
.then(result => console.log(result))
.catch(error => console.error(error.message));
Promise States
Three states: pending → fulfilled or rejected. Once settled, never changes.
let p = new Promise((resolve) => {
setTimeout(() => resolve("Done"), 1000);
});
Promise Chaining
Return values from .then() pass to the next .then().
fetchUser()
.then(user => fetchPosts(user.id))
.then(posts => console.log(posts))
.catch(error => console.error(error.message));
Tip: A single .catch() at the end handles errors from any step.
Promise.all()
Run multiple promises in parallel. Fails fast if any rejects.
Promise.all([fetch("/api/users"), fetch("/api/posts")])
.then(([users, posts]) => console.log(users, posts))
.catch(error => console.error("One failed:", error.message));
Promise.allSettled()
Wait for all, regardless of success or failure.
Promise.allSettled([p1, p2, p3]).then(results => {
results.forEach(r => console.log(r.status, r.value || r.reason));
});
Promise.race() and Promise.any()
race() — first to settle wins. any() — first to fulfill wins (ignores rejections).
Promise.race([fast, slow]).then(result => console.log(result));
Promise.any([p1, p2, p3]).then(result => console.log(result));
Data Fetcher Example
class DataFetcher {
#baseUrl;
constructor(baseUrl) { this.#baseUrl = baseUrl; }
get(endpoint) {
return fetch(`${this.#baseUrl}${endpoint}`)
.then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); });
}
fetchAll(endpoints) {
return Promise.all(endpoints.map(e => this.get(e)));
}
}
File Processing Pipeline
readFile("input.txt")
.then(data => processFile(data))
.then(processed => saveFile("output.txt", processed))
.then(result => console.log(result))
.catch(error => console.error(error));
Best Practices
- Always handle errors — Use
.catch()or try/catch - Chain promises — Avoid nested
.then() - Use
Promise.all()— For parallel operations - Use
finally— For cleanup that always runs
Common Mistakes
- Forgetting
returnin.then()— Returns undefined - Not handling errors — Unhandled rejections
- Nested promises — Hard to read
- Ignoring rejections — Silent failures