-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04-promises.js
More file actions
367 lines (309 loc) · 11 KB
/
04-promises.js
File metadata and controls
367 lines (309 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
// 04-promises.js
// Demonstrates promises, states, chaining, and static methods
console.log("🤝 Starting demonstration of promises\n");
// ============================================================================
// WHAT IS A PROMISE?
// ============================================================================
console.log("1️⃣ What is a Promise?");
// Think of it like a roommate promising to get tacos
const tacoPromise = new Promise((resolve, reject) => {
console.log("🌮 Roommate is going to get tacos...");
// Simulate roommate going to get tacos
setTimeout(() => {
const gotTacos = Math.random() > 0.5; // 50% chance
if (gotTacos) {
resolve("🌮 Tacos acquired!");
} else {
reject("😞 No tacos available");
}
}, 2000);
});
// Using the promise
tacoPromise
.then(result => {
console.log("✅ Success:", result);
})
.catch(error => {
console.log("❌ Error:", error);
});
// ============================================================================
// PROMISE STATES
// ============================================================================
console.log("\n2️⃣ Promise States:");
// Promise has 3 states: Pending, Fulfilled, Rejected
const statePromise = new Promise((resolve, reject) => {
console.log("⏳ Promise starts in 'pending' state");
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
console.log("✅ Changing to 'fulfilled' state");
resolve("Success!");
} else {
console.log("❌ Changing to 'rejected' state");
reject("Error!");
}
}, 1000);
});
statePromise
.then(result => {
console.log("🎉 Promise fulfilled with:", result);
})
.catch(error => {
console.log("💥 Promise rejected with:", error);
});
// ============================================================================
// CREATING AND USING PROMISES
// ============================================================================
console.log("\n3️⃣ Creating and Using Promises:");
// Creating a promise
function createPromise(success = true) {
return new Promise((resolve, reject) => {
console.log("🔄 Creating promise...");
setTimeout(() => {
if (success) {
resolve("🎉 Operation successful!");
} else {
reject("💥 Operation failed!");
}
}, 1000);
});
}
// Using promises
const successPromise = createPromise(true);
const failurePromise = createPromise(false);
successPromise
.then(result => {
console.log("✅ Success promise:", result);
})
.catch(error => {
console.log("❌ Success promise error:", error);
});
failurePromise
.then(result => {
console.log("✅ Failure promise:", result);
})
.catch(error => {
console.log("❌ Failure promise error:", error);
});
// ============================================================================
// PROMISE CHAINING
// ============================================================================
console.log("\n4️⃣ Promise Chaining:");
// Simulated API functions that return promises
function fetchUser(userId) {
return new Promise((resolve, reject) => {
console.log(`👤 Fetching user ${userId}...`);
setTimeout(() => {
resolve({ id: userId, name: "Alice", email: "alice@example.com" });
}, 1000);
});
}
function fetchUserPosts(userId) {
return new Promise((resolve, reject) => {
console.log(`📝 Fetching posts for user ${userId}...`);
setTimeout(() => {
resolve([
{ id: 1, title: "First Post", userId: userId },
{ id: 2, title: "Second Post", userId: userId }
]);
}, 1000);
});
}
function fetchPostComments(postId) {
return new Promise((resolve, reject) => {
console.log(`💬 Fetching comments for post ${postId}...`);
setTimeout(() => {
resolve([
{ id: 1, text: "Great post!", postId: postId },
{ id: 2, text: "Thanks for sharing!", postId: postId }
]);
}, 1000);
});
}
// ✅ Clean promise chain (solves callback hell)
console.log("✅ Promise chain example:");
fetchUser(123)
.then(user => {
console.log("👤 User:", user);
return fetchUserPosts(user.id);
})
.then(posts => {
console.log("📝 Posts:", posts);
return fetchPostComments(posts[0].id);
})
.then(comments => {
console.log("💬 Comments:", comments);
console.log("✅ All data fetched successfully!");
})
.catch(error => {
console.log("❌ Error in chain:", error);
});
// ============================================================================
// STATIC PROMISE METHODS
// ============================================================================
console.log("\n5️⃣ Static Promise Methods:");
// Promise.all() - Wait for all promises
const promises = [
new Promise(resolve => setTimeout(() => resolve("User data"), 1000)),
new Promise(resolve => setTimeout(() => resolve("Post data"), 1500)),
new Promise(resolve => setTimeout(() => resolve("Comment data"), 2000))
];
Promise.all(promises)
.then(results => {
console.log("📊 Promise.all results:", results);
})
.catch(error => {
console.log("❌ Promise.all error:", error);
});
// Promise.race() - Wait for first promise
const racePromises = [
new Promise(resolve => setTimeout(() => resolve("Fast"), 1000)),
new Promise(resolve => setTimeout(() => resolve("Slow"), 3000))
];
Promise.race(racePromises)
.then(result => {
console.log("🏁 Promise.race winner:", result);
});
// Promise.allSettled() - Wait for all, regardless of success/failure
const mixedPromises = [
Promise.resolve("Success 1"),
Promise.reject("Error 1"),
Promise.resolve("Success 2"),
Promise.reject("Error 2")
];
Promise.allSettled(mixedPromises)
.then(results => {
console.log("📋 Promise.allSettled results:");
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(` ✅ Promise ${index} succeeded:`, result.value);
} else {
console.log(` ❌ Promise ${index} failed:`, result.reason);
}
});
});
// ============================================================================
// ERROR HANDLING
// ============================================================================
console.log("\n6️⃣ Error Handling:");
// Promise with error
const errorPromise = new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error("Something went wrong"));
}, 1000);
});
// Using .catch() for error handling
errorPromise
.then(result => {
console.log("✅ This won't run");
})
.catch(error => {
console.log("❌ Caught error:", error.message);
});
// Error in .then() callback
new Promise(resolve => resolve("Success"))
.then(result => {
console.log("✅ Got result:", result);
throw new Error("Error in .then()");
})
.catch(error => {
console.log("❌ Caught error from .then():", error.message);
});
// ============================================================================
// REAL-WORLD EXAMPLE
// ============================================================================
console.log("\n7️⃣ Real-world example - API calls:");
// Simulated API functions
function apiCall(endpoint, delay = 1000) {
return new Promise((resolve, reject) => {
console.log(`📡 Calling API: ${endpoint}`);
setTimeout(() => {
const success = Math.random() > 0.2; // 80% success rate
if (success) {
resolve({ endpoint, data: `Data from ${endpoint}` });
} else {
reject(new Error(`Failed to fetch ${endpoint}`));
}
}, delay);
});
}
// Sequential API calls
async function sequentialCalls() {
try {
console.log("🔄 Sequential API calls:");
const user = await apiCall("/api/user", 1000);
console.log("✅ User loaded");
const posts = await apiCall("/api/posts", 1500);
console.log("✅ Posts loaded");
const comments = await apiCall("/api/comments", 2000);
console.log("✅ Comments loaded");
console.log("🎉 All sequential calls completed!");
} catch (error) {
console.log("❌ Sequential calls error:", error.message);
}
}
// Concurrent API calls
async function concurrentCalls() {
try {
console.log("🔄 Concurrent API calls:");
const [user, posts, comments] = await Promise.all([
apiCall("/api/user", 1000),
apiCall("/api/posts", 1500),
apiCall("/api/comments", 2000)
]);
console.log("🎉 All concurrent calls completed!");
console.log("📊 Results:", { user, posts, comments });
} catch (error) {
console.log("❌ Concurrent calls error:", error.message);
}
}
// Start the examples
setTimeout(() => {
sequentialCalls();
}, 8000);
setTimeout(() => {
concurrentCalls();
}, 12000);
// ============================================================================
// PROMISE UTILITIES
// ============================================================================
console.log("\n8️⃣ Promise utilities:");
// Promise.resolve() - Create resolved promise
Promise.resolve("Immediate success")
.then(result => console.log("✅ Resolved:", result));
// Promise.reject() - Create rejected promise
Promise.reject(new Error("Immediate failure"))
.catch(error => console.log("❌ Rejected:", error.message));
// Converting callback-based API to promise
function callbackToPromise(callbackFunction) {
return new Promise((resolve, reject) => {
callbackFunction((error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}
// Example usage
const callbackAPI = (callback) => {
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
callback(null, "Callback success");
} else {
callback(new Error("Callback error"), null);
}
}, 1000);
};
callbackToPromise(callbackAPI)
.then(result => console.log("✅ Converted callback:", result))
.catch(error => console.log("❌ Converted callback error:", error.message));
console.log("\n📊 Expected behavior:");
console.log("- Promises start in 'pending' state");
console.log("- They transition to 'fulfilled' or 'rejected'");
console.log("- Promise.all waits for all promises");
console.log("- Promise.race returns the first to complete");
console.log("- Promise.allSettled waits for all regardless of outcome");
console.log("- Chaining makes async code more readable");