Promises
📖 Concept
A Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It's a placeholder for a future value.
States: Pending → Fulfilled (resolved) OR Rejected. Once settled, a Promise is immutable.
Creating: new Promise((resolve, reject) => { ... })
Consuming: .then(), .catch(), .finally()
Combinators:
Promise.all()— Wait for ALL to resolve (fails fast on any rejection)Promise.allSettled()— Wait for ALL to settle (never rejects)Promise.race()— First to settle winsPromise.any()— First to RESOLVE wins (ignores rejections)
🏠 Real-world analogy: A Promise is like ordering food online. You get an order confirmation (Promise). It's either delivered (resolved) or cancelled (rejected). You can set up actions for both outcomes. And Promise.all is like waiting for your entire group order — everyone's food must arrive before you eat.
💻 Code Example
1// Creating a Promise2const fetchUser = (id) => new Promise((resolve, reject) => {3 setTimeout(() => {4 if (id <= 0) reject(new Error("Invalid ID"));5 else resolve({ id, name: "Alice", age: 25 });6 }, 1000);7});89// Consuming10fetchUser(1)11 .then(user => {12 console.log("User:", user);13 return user.id; // Return value becomes next .then's input14 })15 .then(id => console.log("User ID:", id))16 .catch(err => console.error("Error:", err.message))17 .finally(() => console.log("Done!"));1819// Promise chaining — sequential async operations20function getUser(id) {21 return Promise.resolve({ id, name: "Alice" });22}23function getPosts(userId) {24 return Promise.resolve([{ id: 1, title: "Post 1" }]);25}26function getComments(postId) {27 return Promise.resolve([{ text: "Nice!" }]);28}2930getUser(1)31 .then(user => getPosts(user.id))32 .then(posts => getComments(posts[0].id))33 .then(comments => console.log(comments))34 .catch(err => console.error(err));3536// Promise.all — parallel execution, fail fast37const [users, posts, settings] = await Promise.all([38 fetch("/api/users").then(r => r.json()),39 fetch("/api/posts").then(r => r.json()),40 fetch("/api/settings").then(r => r.json())41]);4243// Promise.allSettled — get results of ALL, even failures44const results = await Promise.allSettled([45 fetch("/api/users"),46 fetch("/api/bad-endpoint"),47 fetch("/api/posts")48]);49results.forEach(result => {50 if (result.status === "fulfilled") console.log("✅", result.value);51 else console.log("❌", result.reason);52});5354// Promise.race — first to settle wins55const result = await Promise.race([56 fetch("/api/primary"),57 new Promise((_, reject) =>58 setTimeout(() => reject(new Error("Timeout")), 5000)59 )60]);6162// Promise.any — first to RESOLVE wins63const fastest = await Promise.any([64 fetch("https://cdn1.example.com/data"),65 fetch("https://cdn2.example.com/data"),66 fetch("https://cdn3.example.com/data")67]);
🏋️ Practice Exercise
Mini Exercise:
- Create a
delay(ms)function that returns a Promise - Implement a timeout wrapper: if a Promise doesn't resolve in N seconds, reject
- Write a function that retries a Promise-based operation up to N times
- Use
Promise.allSettledto fetch from multiple APIs and handle partial failures
⚠️ Common Mistakes
Not returning Promises in
.then()chains — the next.then()receivesundefinedForgetting
.catch()at the end of a chain — unhandled rejections crash Node.js or show console warningsCreating a Promise inside a
.then()without returning it — creates a 'floating' PromiseUsing
Promise.allwhen one failure shouldn't stop everything — usePromise.allSettledinsteadResolving a Promise with a Promise — it actually waits for the inner Promise to settle (auto-unwrapping)
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Promises. Login to unlock this feature.