-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path05-async-await.js
More file actions
385 lines (312 loc) Β· 11.1 KB
/
05-async-await.js
File metadata and controls
385 lines (312 loc) Β· 11.1 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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// 05-async-await.js
// Demonstrates async/await syntax, patterns, and error handling
console.log("β³ Starting demonstration of async/await\n");
// ============================================================================
// THE ASYNC KEYWORD
// ============================================================================
console.log("1οΈβ£ The async keyword:");
// async functions always return promises
async function greet() {
return "π Hello from async function!";
}
// Equivalent to:
function greetPromise() {
return Promise.resolve("π Hello from promise function!");
}
// Using async functions
greet().then(message => {
console.log("β
Async function result:", message);
});
greetPromise().then(message => {
console.log("β
Promise function result:", message);
});
// ============================================================================
// THE AWAIT KEYWORD
// ============================================================================
console.log("\n2οΈβ£ The await keyword:");
// Simulated API functions
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);
});
}
// Using await (looks synchronous!)
async function fetchUserData() {
try {
console.log("π Starting to fetch user data...");
const user = await fetchUser(123);
console.log("π€ User loaded:", user);
const posts = await fetchUserPosts(user.id);
console.log("π Posts loaded:", posts);
return { user, posts };
} catch (error) {
console.log("β Error:", error.message);
}
}
// Call the async function
fetchUserData().then(result => {
if (result) {
console.log("β
Final result:", result);
}
});
// ============================================================================
// EXECUTION PATTERNS
// ============================================================================
console.log("\n3οΈβ£ Execution Patterns:");
// Simulated API functions with different delays
function apiCall(endpoint, delay = 1000) {
return new Promise((resolve, reject) => {
console.log(`π‘ Calling ${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 Execution
async function sequentialExecution() {
console.log("π Sequential execution:");
const start = Date.now();
const result1 = await apiCall("/api/data1", 2000);
console.log("β
First request done");
const result2 = await apiCall("/api/data2", 1000);
console.log("β
Second request done");
const result3 = await apiCall("/api/data3", 1500);
console.log("β
Third request done");
const totalTime = Date.now() - start;
console.log(`β±οΈ Total time: ${totalTime}ms (sequential)`);
return [result1, result2, result3];
}
// Concurrent Execution
async function concurrentExecution() {
console.log("π Concurrent execution:");
const start = Date.now();
// Start all requests at the same time
const promise1 = apiCall("/api/data1", 2000);
const promise2 = apiCall("/api/data2", 1000);
const promise3 = apiCall("/api/data3", 1500);
// Wait for all to complete
const [result1, result2, result3] = await Promise.all([promise1, promise2, promise3]);
const totalTime = Date.now() - start;
console.log(`β±οΈ Total time: ${totalTime}ms (concurrent)`);
return [result1, result2, result3];
}
// Start the execution pattern examples
setTimeout(() => {
sequentialExecution();
}, 5000);
setTimeout(() => {
concurrentExecution();
}, 10000);
// ============================================================================
// ERROR HANDLING
// ============================================================================
console.log("\n4οΈβ£ Error handling with async/await:");
// Function that might fail
function riskyOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve("π Operation successful!");
} else {
reject(new Error("π₯ Operation failed!"));
}
}, 1000);
});
}
// Error handling with try/catch
async function handleErrors() {
try {
console.log("π Attempting risky operation...");
const result = await riskyOperation();
console.log("β
Success:", result);
} catch (error) {
console.log("β Error caught:", error.message);
}
}
// Multiple error handling approaches
async function multipleErrorHandling() {
// Approach 1: try/catch
try {
const result1 = await riskyOperation();
console.log("β
Try/catch success:", result1);
} catch (error) {
console.log("β Try/catch error:", error.message);
}
// Approach 2: .catch() on the promise
const result2 = await riskyOperation().catch(error => {
console.log("β .catch() error:", error.message);
return "Fallback value";
});
console.log("β
.catch() result:", result2);
}
// Start error handling examples
setTimeout(() => {
handleErrors();
}, 15000);
setTimeout(() => {
multipleErrorHandling();
}, 17000);
// ============================================================================
// REAL-WORLD EXAMPLE
// ============================================================================
console.log("\n5οΈβ£ Real-world example - User profile loading:");
async function loadUserProfile(userId) {
try {
console.log(`π Loading profile for user ${userId}...`);
// Start all requests concurrently
const [user, posts, followers] = await Promise.all([
fetchUser(userId),
fetchUserPosts(userId),
fetchFollowers(userId)
]);
console.log("β
All profile data loaded!");
return {
user,
posts,
followers
};
} catch (error) {
console.error("β Failed to load profile:", error.message);
throw error;
}
}
// Helper function for followers
function fetchFollowers(userId) {
return new Promise((resolve, reject) => {
console.log(`π₯ Fetching followers for user ${userId}...`);
setTimeout(() => {
resolve([
{ id: 101, name: "Bob" },
{ id: 102, name: "Charlie" },
{ id: 103, name: "Diana" }
]);
}, 1200);
});
}
// Using the profile loader
setTimeout(() => {
loadUserProfile(123)
.then(profile => {
console.log("π Complete profile:", profile);
})
.catch(error => {
console.log("β Profile loading failed:", error.message);
});
}, 20000);
// ============================================================================
// ADVANCED PATTERNS
// ============================================================================
console.log("\n6οΈβ£ Advanced patterns:");
// Parallel execution with error handling
async function parallelWithErrorHandling() {
console.log("π Parallel execution with error handling:");
const promises = [
apiCall("/api/users").catch(e => ({ error: e.message })),
apiCall("/api/posts").catch(e => ({ error: e.message })),
apiCall("/api/comments").catch(e => ({ error: e.message }))
];
const results = await Promise.all(promises);
results.forEach((result, index) => {
if (result.error) {
console.log(`β API ${index + 1} failed:`, result.error);
} else {
console.log(`β
API ${index + 1} succeeded:`, result.data);
}
});
}
// Sequential with early exit
async function sequentialWithEarlyExit() {
console.log("π Sequential with early exit:");
try {
const user = await apiCall("/api/user");
console.log("β
User loaded");
if (!user.data) {
throw new Error("No user data");
}
const posts = await apiCall("/api/posts");
console.log("β
Posts loaded");
const comments = await apiCall("/api/comments");
console.log("β
Comments loaded");
console.log("π All data loaded successfully!");
} catch (error) {
console.log("β Early exit due to error:", error.message);
}
}
// Start advanced patterns
setTimeout(() => {
parallelWithErrorHandling();
}, 25000);
setTimeout(() => {
sequentialWithEarlyExit();
}, 30000);
// ============================================================================
// ASYNC/AWAIT VS PROMISES
// ============================================================================
console.log("\n7οΈβ£ Async/await vs Promises comparison:");
// Promise chain approach
function promiseChain() {
return fetchUser(123)
.then(user => {
console.log("π€ User (promise):", user);
return fetchUserPosts(user.id);
})
.then(posts => {
console.log("π Posts (promise):", posts);
return fetchPostComments(posts[0].id);
})
.then(comments => {
console.log("π¬ Comments (promise):", comments);
})
.catch(error => {
console.log("β Promise chain error:", error.message);
});
}
// Async/await approach
async function asyncAwaitApproach() {
try {
const user = await fetchUser(123);
console.log("π€ User (async):", user);
const posts = await fetchUserPosts(user.id);
console.log("π Posts (async):", posts);
const comments = await fetchPostComments(posts[0].id);
console.log("π¬ Comments (async):", comments);
} catch (error) {
console.log("β Async/await error:", error.message);
}
}
// Start comparison
setTimeout(() => {
console.log("π Promise chain approach:");
promiseChain();
}, 35000);
setTimeout(() => {
console.log("π Async/await approach:");
asyncAwaitApproach();
}, 40000);
console.log("\nπ Expected behavior:");
console.log("- Async functions always return promises");
console.log("- Await pauses execution until promise settles");
console.log("- Sequential execution waits for each operation");
console.log("- Concurrent execution runs operations in parallel");
console.log("- Try/catch provides clean error handling");
console.log("- Async/await makes code look synchronous");