-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcallbacks.js
More file actions
71 lines (52 loc) · 1.35 KB
/
callbacks.js
File metadata and controls
71 lines (52 loc) · 1.35 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
// CALLBACKS IN Js
// A callback is a function passed as an argument to another function,
// which is then executed later (usually after an asynchronous operation).
// Callbacks were the earliest way to handle async code before Promises and async/await.
// EXAMPLE 1: SIMPLE CALLBACK
function greetUser(name, callback) {
console.log("Hi", name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greetUser("David", sayBye);//output Hi David
// EXAMPLE 2: CALLBACK WITH A DELAY (ASYNC BEHAVIOR)
function fetchData(callback) {
console.log("Fetching data...");
setTimeout(() => {
console.log(" Data fetched!");
callback("Here is your data");
}, 2000);
}
fetchData((data) => {
console.log("Received:", data);
});
// EXAMPLE 3: CALLBACK HELL (NESTED CALLBACKS)
// Multiple callbacks lead to hard-to-read code (known as callback hell).
function stepOne(callback) {
setTimeout(() => {
console.log("Step 1 complete");
callback();
}, 1000);
}
function stepTwo(callback) {
setTimeout(() => {
console.log("Step 2 complete");
callback();
}, 1000);
}
function stepThree(callback) {
setTimeout(() => {
console.log("Step 3 complete");
callback();
}, 1000);
}
// Nested callbacks (messy structure)
stepOne(() => {
stepTwo(() => {
stepThree(() => {
console.log("All steps done!");
});
});
});