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 wins
  • Promise.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

codeTap to expand ⛶
1// Creating a Promise
2const 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});
8
9// Consuming
10fetchUser(1)
11 .then(user => {
12 console.log("User:", user);
13 return user.id; // Return value becomes next .then's input
14 })
15 .then(id => console.log("User ID:", id))
16 .catch(err => console.error("Error:", err.message))
17 .finally(() => console.log("Done!"));
18
19// Promise chaining — sequential async operations
20function 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}
29
30getUser(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));
35
36// Promise.all — parallel execution, fail fast
37const [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]);
42
43// Promise.allSettled — get results of ALL, even failures
44const 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});
53
54// Promise.race — first to settle wins
55const result = await Promise.race([
56 fetch("/api/primary"),
57 new Promise((_, reject) =>
58 setTimeout(() => reject(new Error("Timeout")), 5000)
59 )
60]);
61
62// Promise.any — first to RESOLVE wins
63const 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:

  1. Create a delay(ms) function that returns a Promise
  2. Implement a timeout wrapper: if a Promise doesn't resolve in N seconds, reject
  3. Write a function that retries a Promise-based operation up to N times
  4. Use Promise.allSettled to fetch from multiple APIs and handle partial failures

⚠️ Common Mistakes

  • Not returning Promises in .then() chains — the next .then() receives undefined

  • Forgetting .catch() at the end of a chain — unhandled rejections crash Node.js or show console warnings

  • Creating a Promise inside a .then() without returning it — creates a 'floating' Promise

  • Using Promise.all when one failure shouldn't stop everything — use Promise.allSettled instead

  • Resolving 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.