-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpromises.js
More file actions
143 lines (111 loc) · 3.5 KB
/
promises.js
File metadata and controls
143 lines (111 loc) · 3.5 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
// A Promise is a special JavaScript object that represents a value
// which may be available now, later, or never.
// Promises make handling asynchronous tasks easier and help avoid "callback hell".
// A Promise can be in one of three states:
// 1.Pending → The operation has not completed yet.
// 2.Fulfilled → The operation completed successfully (resolved).
// 3. Rejected → The operation failed (rejected).
// CREATING A SIMPLE PROMISE
const myPromise = new Promise((resolve, reject) => {
let success = true;
setTimeout(() => {
if (success) {
resolve(" Operation successful!");
} else {
reject(" Something went wrong!");
}
}, 2000);
});
// Handling the Promise result
myPromise
.then((result) => console.log(result)) // Runs if resolved
.catch((error) => console.log(error)) // Runs if rejected
.finally(() => console.log("Completed!")); // Always runs
// WHY USE PROMISES?
// Without promises, we would need nested callbacks (callback hell).
// Promises flatten that structure, making async code easier to read and maintain.
// EXAMPLE: Simulating a Network Request
function fetchUserData() {
return new Promise((resolve, reject) => {
console.log(" Fetching user...");
setTimeout(() => {
const success = true;
if (success) {
resolve({ name: "David", role: "Developer" });
} else {
reject("Failed to fetch user!");
}
}, 1500);
});
}
// Consuming the Promise
fetchUserData()
.then((user) => {
console.log("User fetched:", user);
return `${user.name} is a ${user.role}`;
})
.then((message) => {
console.log("Message:", message);
})
.catch((err) => {
console.error(err);
})
.finally(() => {
console.log("Fetch attempt finished.");
});
// CHAINING PROMISES
// You can chain multiple .then() calls to perform sequential async operations.
function stepOne() {
return new Promise((resolve) => {
setTimeout(() => resolve("Step 1 "), 1000);
});
}
function stepTwo() {
return new Promise((resolve) => {
setTimeout(() => resolve("Step 2 "), 1000);
});
}
function stepThree() {
return new Promise((resolve) => {
setTimeout(() => resolve("Step 3 "), 1000);
});
}
stepOne()
.then((result) => {
console.log(result);
return stepTwo();
})
.then((result) => {
console.log(result);
return stepThree();
})
.then((result) => {
console.log(result);
console.log(" All steps complete!");
});
// Promise.all()
// Runs multiple promises in parallel and waits for all to complete.
const promise1 = Promise.resolve("Apple");
const promise2 = Promise.resolve("Banana");
const promise3 = new Promise((resolve) =>
setTimeout(() => resolve(" Grape"), 1000)
);
Promise.all([promise1, promise2, promise3]).then((values) =>
console.log("All fruits:", values)
);
// Promise.race()
// Returns the result of the first promise that settles (fulfilled or rejected).
const slow = new Promise((resolve) =>
setTimeout(() => resolve(" Slow"), 2000)
);
const fast = new Promise((resolve) =>
setTimeout(() => resolve(" Fast"), 1000)
);
Promise.race([slow, fast]).then((value) => console.log("Winner:", value));
//Conclusion
// Promises represent async values that may complete in the future.
// They have three states: pending, fulfilled, rejected.
// Use .then() for success, .catch() for errors, and .finally() for cleanup.
// You can chain promises for sequential operations.
// Promise.all() → Runs tasks in parallel.
// Promise.race() → Resolves with the first completed task.