-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19-Asynchronous-JavaScript-Basics.js
More file actions
100 lines (77 loc) · 2.27 KB
/
19-Asynchronous-JavaScript-Basics.js
File metadata and controls
100 lines (77 loc) · 2.27 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
// ===============================
// SYNCHRONOUS CODE (BLOCKING)
// ===============================
// These lines run one after another in order
// JavaScript will not skip or delay them
console.log("start");
console.log("middle");
console.log("End");
// ===============================
// ASYNCHRONOUS CODE (NON-BLOCKING)
// ===============================
console.log("Start");
// This runs first because it is synchronous
// setTimeout is asynchronous
// It sends the task to the Web APIs and does NOT block the main thread
setTimeout(() => {
console.log("4000");
}, 4000); // runs after 4 seconds
setTimeout(() => {
console.log("2000");
}, 2000); // runs after 2 seconds
setTimeout(() => {
console.log("3000");
}, 3000); // runs after 3 seconds
setTimeout(() => {
console.log("1000");
}, 1000); // runs after 1 second
console.log("End");
// This runs immediately after "Start"
// JavaScript does NOT wait for setTimeout
// ===============================
// CALLBACK FUNCTION EXAMPLE
// ===============================
// This function accepts another function as an argument
// That function is called a CALLBACK
function fetchData(callback) {
// Simulating data fetching with setTimeout
setTimeout(() => {
callback("Data Received"); // callback runs AFTER async task
}, 1000);
}
// Passing a function as a callback
fetchData((result) => {
console.log("Result: " + result);
});
// ===============================
// CALLBACK HELL EXAMPLE
// ===============================
// Multiple async operations depending on each other
// This creates deeply nested callbacks
login(user, () => {
getProfile(() => {
getPosts(() => {
getComments(() => {
console.log("Done");
});
});
});
});
// This structure is hard to read, debug, and maintain
// This problem is called CALLBACK HELL
// ===============================
// PROMISE EXAMPLE (MODERN WAY)
// ===============================
// Creating a Promise
// resolve → success
// reject → error
const tempPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success"); // promise fulfilled
}, 1000);
});
// Handling the resolved value using .then()
tempPromise.then((result) => {
console.log(result);
});
// Promises avoid deep nesting and make async code cleaner