Skip to content

Commit a892720

Browse files
promises in JS
1 parent 837cb21 commit a892720

File tree

5 files changed

+587
-1
lines changed

5 files changed

+587
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ Welcome to your comprehensive JavaScript interview notes! This repository contai
1111
- [Higher Order Functions](JS-Interview-Questions/HigherOrderFunction.md)
1212
- [Map, Reduce, Filter](JS-Interview-Questions/map-reduce-filters.md)
1313
- [Polyfills](HigherOrderFunction/polyfills.html)
14-
14+
- [Promises](promises/promises.md)
1515
- [More Topics Coming Soon!]
1616

1717
---
@@ -41,6 +41,7 @@ Welcome to your comprehensive JavaScript interview notes! This repository contai
4141
- [Higher Order Functions](JS-Interview-Questions/HigherOrderFunction.md)
4242
- [Map, Reduce, Filter](JS-Interview-Questions/map-reduce-filters.md)
4343
- [Polyfills](HigherOrderFunction/polyfills.html)
44+
- [Promises](promises/promises.md)
4445

4546
---
4647

index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
- [Higher Order Functions](JS-Interview-Questions/HigherOrderFunction.md)
99
- [Map, Reduce, Filter](JS-Interview-Questions/map-reduce-filters.md)
1010
- [Polyfills](HigherOrderFunction/polyfills.html)
11+
- [Promises](promises/promises.md)
1112
- [More Topics Coming Soon!]
1213

1314
---

promises/Promises.js

Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
2+
const githubUserInfoURL = "https://api.github.com/users/adityasrivastava29";
3+
4+
const user = fetch(githubUserInfoURL);
5+
6+
7+
console.log(user); // This will log a Promise object
8+
user.then((response) => {
9+
return response.json(); // Convert the response to JSON
10+
}).then((data) => {
11+
console.log(data); // This will log the user data
12+
document.getElementById('userinfo').innerHTML = `
13+
<h1> User information from github api using promises</h1>
14+
<img src="${data.avatar_url}" alt="Avatar" style="width: 100px; height: 100px; border-radius: 50%;">
15+
<h2>${data.name}</h2>
16+
<p>Username: ${data.login}</p>
17+
<p>Bio: ${data.bio}</p>
18+
<p>Location: ${data.location}</p>
19+
<p>Followers: ${data.followers}</p>
20+
<p>Following: ${data.following}</p>
21+
`; // Display user data in the HTML
22+
}).catch((error) => {
23+
console.error("Error fetching user data:", error); // Handle any errors
24+
}); // Catch any errors in the promise chain
25+
26+
27+
28+
// 1. CREATING A BASIC PROMISE
29+
// This is a simple promise that resolves after 1 second
30+
// It simulates an asynchronous operation
31+
// This is a basic example of how promises work in JavaScript
32+
const myPromise = new Promise((resolve, reject) => {
33+
const success = true; // Simulate success/failure
34+
35+
setTimeout(() => {
36+
if (success) {
37+
resolve("Operation successful!"); // Fulfill the promise
38+
} else {
39+
reject("Operation failed!"); // Reject the promise
40+
}
41+
}, 1000);
42+
});
43+
44+
// Using the promise
45+
myPromise
46+
.then(result => console.log(result + " ---- This is the result of the promise"))
47+
.catch(error => console.error(error));
48+
49+
// 2. REAL-WORLD EXAMPLE - API CALL SIMULATION
50+
function fetchUserData(userId) {
51+
return new Promise((resolve, reject) => {
52+
// Simulate API call delay
53+
setTimeout(() => {
54+
if (userId > 0) {
55+
resolve({
56+
id: userId,
57+
name: "Aditya Kumar",
58+
59+
});
60+
} else {
61+
reject(new Error("Invalid user ID"));
62+
}
63+
}, 1500);
64+
});
65+
}
66+
67+
// 3. PROMISE CHAINING
68+
fetchUserData(1)
69+
.then(user => {
70+
console.log("User fetched:", user);
71+
// Return another promise
72+
return fetchUserPosts(user.id);
73+
})
74+
.then(posts => {
75+
console.log("Posts fetched:", posts);
76+
return posts.length;
77+
})
78+
.then(postCount => {
79+
console.log("Total posts:", postCount);
80+
})
81+
.catch(error => {
82+
console.error("Error in chain:", error.message);
83+
});
84+
85+
function fetchUserPosts(userId) {
86+
return new Promise(resolve => {
87+
setTimeout(() => {
88+
resolve([
89+
{ id: 1, title: "First Post" },
90+
{ id: 2, title: "Second Post" }
91+
]);
92+
}, 1000);
93+
});
94+
}
95+
96+
// 4. PROMISE.ALL() - PARALLEL EXECUTION
97+
const promise1 = fetchUserData(1);
98+
const promise2 = fetchUserData(2);
99+
const promise3 = fetchUserData(3);
100+
101+
Promise.all([promise1, promise2, promise3])
102+
.then(users => {
103+
console.log("All users fetched:", users);
104+
})
105+
.catch(error => {
106+
console.error("One or more promises failed:", error);
107+
});
108+
109+
// 5. PROMISE.ALLSETTLED() - HANDLE BOTH SUCCESS AND FAILURE
110+
Promise.allSettled([
111+
fetchUserData(1),
112+
fetchUserData(-1), // This will fail
113+
fetchUserData(2)
114+
])
115+
.then(results => {
116+
results.forEach((result, index) => {
117+
if (result.status === 'fulfilled') {
118+
console.log(`Promise ${index} succeeded:`, result.value);
119+
} else {
120+
console.log(`Promise ${index} failed:`, result.reason.message);
121+
}
122+
});
123+
});
124+
125+
// 6. PROMISE.RACE() - FIRST TO COMPLETE WINS
126+
const slowPromise = new Promise(resolve =>
127+
setTimeout(() => resolve("Slow"), 3000)
128+
);
129+
const fastPromise = new Promise(resolve =>
130+
setTimeout(() => resolve("Fast"), 1000)
131+
);
132+
133+
Promise.race([slowPromise, fastPromise])
134+
.then(result => console.log("Winner:", result)); // "Fast"
135+
136+
// 7. ERROR HANDLING PATTERNS
137+
function handleAsyncOperation() {
138+
return fetchUserData(1)
139+
.then(user => {
140+
if (!user.email) {
141+
throw new Error("User has no email");
142+
}
143+
return user;
144+
})
145+
.catch(error => {
146+
console.error("Handling error:", error.message);
147+
// Return default user or re-throw
148+
return { id: 0, name: "Guest", email: "[email protected]" };
149+
});
150+
}
151+
152+
// 8. CONVERTING CALLBACKS TO PROMISES
153+
function promisifiedSetTimeout(delay) {
154+
return new Promise(resolve => {
155+
setTimeout(resolve, delay);
156+
});
157+
}
158+
159+
// Usage
160+
promisifiedSetTimeout(2000)
161+
.then(() => console.log("2 seconds have passed"));
162+
163+
// 9. ASYNC/AWAIT WITH PROMISES (Modern approach)
164+
async function modernAsyncFunction() {
165+
try {
166+
const user = await fetchUserData(1);
167+
const posts = await fetchUserPosts(user.id);
168+
console.log("User and posts:", { user, posts });
169+
} catch (error) {
170+
console.error("Async/await error:", error.message);
171+
}
172+
}
173+
174+
// 10. PROMISE FINALLY
175+
fetchUserData(1)
176+
.then(user => console.log("Success:", user))
177+
.catch(error => console.error("Error:", error))
178+
.finally(() => console.log("Cleanup operations"));
179+
180+
// 11. CREATING IMMEDIATELY RESOLVED/REJECTED PROMISES
181+
const resolvedPromise = Promise.resolve("Immediate success");
182+
const rejectedPromise = Promise.reject("Immediate failure");
183+
184+
resolvedPromise.then(console.log); // "Immediate success"
185+
rejectedPromise.catch(console.error); // "Immediate failure"

promises/index.html

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<title>Promises In Javascript</title>
7+
<script src="Promises.js"></script>
8+
</head>
9+
<body>
10+
<h1>Promises In JavaScript</h1>
11+
<div id="userinfo"></div>
12+
</body>
13+
14+
</html>

0 commit comments

Comments
 (0)