-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03-callbacks.js
More file actions
300 lines (247 loc) Β· 8.95 KB
/
03-callbacks.js
File metadata and controls
300 lines (247 loc) Β· 8.95 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
// 03-callbacks.js
// Demonstrates callbacks, callback hell, and solutions
console.log("π Starting demonstration of callbacks\n");
// ============================================================================
// SYNCHRONOUS CALLBACKS
// ============================================================================
console.log("1οΈβ£ Synchronous callbacks (immediate execution):");
const numbers = [1, 2, 3, 4, 5];
// Array methods use synchronous callbacks
const doubled = numbers.map(num => num * 2);
console.log("π Doubled numbers:", doubled);
const filtered = numbers.filter(num => num > 3);
console.log("π Filtered numbers (>3):", filtered);
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log("β Sum of numbers:", sum);
// Custom function with synchronous callback
function processArray(arr, callback) {
const result = [];
for (let i = 0; i < arr.length; i++) {
result.push(callback(arr[i], i, arr));
}
return result;
}
const processed = processArray(numbers, (num, index) => {
return `Item ${index}: ${num}`;
});
console.log("π Custom processed:", processed);
// ============================================================================
// ASYNCHRONOUS CALLBACKS
// ============================================================================
console.log("\n2οΈβ£ Asynchronous callbacks (delayed execution):");
// setTimeout callback
setTimeout(() => {
console.log("β° This runs after 1 second");
}, 1000);
// Simulated API call with callback
function fetchUserData(userId, callback) {
console.log(`π‘ Fetching data for user ${userId}...`);
// Simulate network delay
setTimeout(() => {
const userData = {
id: userId,
name: "John Doe",
email: "john@example.com"
};
// Simulate success/failure
const success = Math.random() > 0.3; // 70% success rate
if (success) {
callback(null, userData);
} else {
callback(new Error("Failed to fetch user data"), null);
}
}, 2000);
}
// Using the async callback
fetchUserData(123, (error, data) => {
if (error) {
console.log("β Error:", error.message);
} else {
console.log("β
User data:", data);
}
});
// ============================================================================
// CALLBACK HELL EXAMPLE
// ============================================================================
console.log("\n3οΈβ£ Callback Hell demonstration:");
// Simulated API functions
function fetchUser(userId, callback) {
setTimeout(() => {
console.log(`π€ Fetching user ${userId}...`);
callback(null, { id: userId, name: "Alice", email: "alice@example.com" });
}, 1000);
}
function fetchUserPosts(userId, callback) {
setTimeout(() => {
console.log(`π Fetching posts for user ${userId}...`);
callback(null, [
{ id: 1, title: "First Post", userId: userId },
{ id: 2, title: "Second Post", userId: userId }
]);
}, 1000);
}
function fetchPostComments(postId, callback) {
setTimeout(() => {
console.log(`π¬ Fetching comments for post ${postId}...`);
callback(null, [
{ id: 1, text: "Great post!", postId: postId },
{ id: 2, text: "Thanks for sharing!", postId: postId }
]);
}, 1000);
}
function fetchCommentAuthor(commentId, callback) {
setTimeout(() => {
console.log(`π€ Fetching author for comment ${commentId}...`);
callback(null, { id: 101, name: "Bob", email: "bob@example.com" });
}, 1000);
}
// β CALLBACK HELL - Hard to read and maintain
console.log("β Callback Hell example:");
fetchUser(123, (userError, user) => {
if (userError) {
console.log("β User error:", userError.message);
return;
}
console.log("π€ User:", user);
fetchUserPosts(user.id, (postsError, posts) => {
if (postsError) {
console.log("β Posts error:", postsError.message);
return;
}
console.log("π Posts:", posts);
fetchPostComments(posts[0].id, (commentsError, comments) => {
if (commentsError) {
console.log("β Comments error:", commentsError.message);
return;
}
console.log("π¬ Comments:", comments);
fetchCommentAuthor(comments[0].id, (authorError, author) => {
if (authorError) {
console.log("β Author error:", authorError.message);
return;
}
console.log("π€ Comment author:", author);
console.log("β
All data fetched successfully!");
});
});
});
});
// ============================================================================
// SOLUTIONS TO CALLBACK HELL
// ============================================================================
console.log("\n4οΈβ£ Solutions to Callback Hell:");
// β
Solution 1: Named functions (better readability)
function handleUser(userError, user) {
if (userError) {
console.log("β User error:", userError.message);
return;
}
console.log("π€ User:", user);
fetchUserPosts(user.id, handlePosts);
}
function handlePosts(postsError, posts) {
if (postsError) {
console.log("β Posts error:", postsError.message);
return;
}
console.log("π Posts:", posts);
fetchPostComments(posts[0].id, handleComments);
}
function handleComments(commentsError, comments) {
if (commentsError) {
console.log("β Comments error:", commentsError.message);
return;
}
console.log("π¬ Comments:", comments);
fetchCommentAuthor(comments[0].id, handleAuthor);
}
function handleAuthor(authorError, author) {
if (authorError) {
console.log("β Author error:", authorError.message);
return;
}
console.log("π€ Comment author:", author);
console.log("β
All data fetched successfully (named functions)!");
}
// Start the named function chain
setTimeout(() => {
console.log("β
Named functions example:");
fetchUser(456, handleUser);
}, 8000);
// ============================================================================
// ERROR HANDLING PATTERNS
// ============================================================================
console.log("\n5οΈβ£ Error handling patterns:");
// Node.js style: error-first callbacks
function nodeStyleCallback(error, data) {
if (error) {
console.log("β Error:", error.message);
return;
}
console.log("β
Data:", data);
}
// Simulate Node.js style API
function nodeStyleAPI(callback) {
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
callback(null, "Success data");
} else {
callback(new Error("Something went wrong"), null);
}
}, 1000);
}
setTimeout(() => {
console.log("π Testing Node.js style callback:");
nodeStyleAPI(nodeStyleCallback);
}, 12000);
// ============================================================================
// REAL-WORLD EXAMPLE
// ============================================================================
console.log("\n6οΈβ£ Real-world example - file processing:");
// Simulated file processing with callbacks
function readFile(filename, callback) {
console.log(`π Reading file: ${filename}`);
setTimeout(() => {
callback(null, `Content of ${filename}`);
}, 1000);
}
function processContent(content, callback) {
console.log("π Processing content...");
setTimeout(() => {
const processed = content.toUpperCase();
callback(null, processed);
}, 500);
}
function saveFile(filename, content, callback) {
console.log(`πΎ Saving to file: ${filename}`);
setTimeout(() => {
callback(null, `Saved ${content.length} characters to ${filename}`);
}, 800);
}
// Chain the operations
readFile("input.txt", (readError, content) => {
if (readError) {
console.log("β Read error:", readError.message);
return;
}
processContent(content, (processError, processed) => {
if (processError) {
console.log("β Process error:", processError.message);
return;
}
saveFile("output.txt", processed, (saveError, result) => {
if (saveError) {
console.log("β Save error:", saveError.message);
return;
}
console.log("β
File processing complete:", result);
});
});
});
console.log("\nπ Expected behavior:");
console.log("- Synchronous callbacks execute immediately");
console.log("- Asynchronous callbacks execute after delays");
console.log("- Callback hell shows nested, hard-to-read code");
console.log("- Named functions improve readability");
console.log("- Error-first pattern is common in Node.js");