Skip to content

Commit 4b9b74b

Browse files
JavaScript: Promises, Promise Functions, Promise Chaining
1 parent 8bedcdc commit 4b9b74b

2 files changed

Lines changed: 308 additions & 0 deletions

File tree

‎JavaScript/Promises.html‎

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
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</title>
7+
</head>
8+
<body>
9+
<script>
10+
/*
11+
# Promises ***: Objects that represent the eventual completion or failure of an asynchronous task
12+
- Properties:
13+
- State:
14+
- Pending
15+
- Resolved (Fulfilled)
16+
- Rejected
17+
- Result: Any value that can be passed along with resolving/rejecting a promise
18+
- Method
19+
- then(): Callback handles the resolved state of the promise
20+
- catch(): Callback handle the rejected state of the promise
21+
22+
- Syntax:
23+
- Creating a promise
24+
const promise1 = new Promise((resolve, reject) => {
25+
// Logic to resolve/reject the promise
26+
})
27+
- Uses the Promise constructor to create a promise object
28+
- Promise constructor takes a callback function with 2 parameters:
29+
- resolve(): Method to resolve the promise
30+
- reject(): Method to reject the promise
31+
- With resolve/reject methods, result value can be passed as an argument
32+
- Handling a promise
33+
promise1.then(() => {
34+
// Logic to handle resolved state
35+
}).catch(() => {
36+
// Logic to handle rejected state
37+
})
38+
- Result can be accessed as the callback parameter for both .then()/ .catch() methods based on resolved/rejected state respectively
39+
*/
40+
41+
// # Example 1 (Synchronous)
42+
// const promise1 = new Promise((resolve, reject) => {
43+
// // resolve()
44+
// reject()
45+
// })
46+
// console.log(promise1)
47+
48+
// const promise1 = new Promise((resolve, reject) => {
49+
// // resolve('Hi')
50+
// reject('Bye')
51+
// })
52+
// console.log(promise1)
53+
54+
// promise1.then(() => {
55+
// console.log('Promise was resolved')
56+
// }).catch(() => {
57+
// console.log('Promise was rejected')
58+
// })
59+
60+
// promise1.then((resolvedResult) => {
61+
// console.log('Promise was resolved', resolvedResult)
62+
// }).catch((rejectedResult) => {
63+
// console.log('Promise was rejected', rejectedResult)
64+
// })
65+
66+
// # Example 2 (Asynchronous)
67+
// const promise1 = new Promise((resolve, reject) => {
68+
// setTimeout(() => {
69+
// resolve('Hi')
70+
// }, 5000)
71+
// })
72+
73+
// promise1.then((resolvedResult) => {
74+
// console.log('Promise resolved after 5 seconds:', resolvedResult)
75+
// }).catch((rejectedResult) => {
76+
// console.log('Promise rejected after 5 seconds:', rejectedResult)
77+
// })
78+
79+
// const fetchStudentsPromise = new Promise((resolve, reject) => {
80+
// const STUDENTS = [
81+
// {
82+
// name: 'Madeline',
83+
// batch: 2,
84+
// course: 'MERN'
85+
// },
86+
// {
87+
// name: 'Simon',
88+
// batch: 5,
89+
// course: 'MEAN'
90+
// },
91+
// {
92+
// name: 'Sonal',
93+
// batch: 2,
94+
// course: 'MEVN'
95+
// }
96+
// ]
97+
98+
// setTimeout(() => {
99+
// // resolve(STUDENTS)
100+
// reject('Server is down!')
101+
// }, 5000)
102+
// })
103+
104+
// console.log('Fetching students ...')
105+
106+
// fetchStudentsPromise.then((resolvedResult) => {
107+
// console.log('Data fetched from the server:', resolvedResult)
108+
// }).catch((error) => {
109+
// console.log('Something went wrong:', error)
110+
// })
111+
112+
// # Promise Function: Function which returns promise object
113+
// const fetchStudents = () => new Promise((resolve, reject) => {
114+
// const STUDENTS = [
115+
// {
116+
// name: 'Madeline',
117+
// batch: 2,
118+
// course: 'MERN'
119+
// },
120+
// {
121+
// name: 'Simon',
122+
// batch: 5,
123+
// course: 'MEAN'
124+
// },
125+
// {
126+
// name: 'Sonal',
127+
// batch: 2,
128+
// course: 'MEVN'
129+
// }
130+
// ]
131+
132+
// console.log('Fetching students ...')
133+
// setTimeout(() => {
134+
// resolve(STUDENTS)
135+
// // reject('Server is down!')
136+
// }, 5000)
137+
// })
138+
139+
// fetchStudents().then((resolvedResult) => {
140+
// console.log('Data fetched from the server:', resolvedResult)
141+
// }).catch((error) => {
142+
// console.log('Something went wrong:', error)
143+
// })
144+
145+
/*
146+
# Promise chaining **:
147+
- Syntax:
148+
promise.then().then().then() ... .catch()
149+
- During promise handling, if .then() returns a new promise, another .then() method needs to be 'chained' to handle this new promise. This pattern continues until there is a .then() method which does not return any promise
150+
151+
*/
152+
// const promise1 = () => new Promise((resolve, reject) => {
153+
// setTimeout(() => {
154+
// resolve()
155+
// }, 5000)
156+
// })
157+
// const promise2 = () => new Promise((resolve, reject) => {
158+
// setTimeout(() => {
159+
// resolve()
160+
// }, 3000)
161+
// })
162+
163+
// promise1().then(() => {
164+
// console.log('Promise 1 resolved')
165+
// return promise2()
166+
// }).then(() => {
167+
// console.log('Promise 2 resolved')
168+
// }).catch(() => {
169+
// console.log('One of the promised was rejected')
170+
// })
171+
172+
/* ---------------------- */
173+
/*
174+
Example: Fetch data from the server, then process that data
175+
1. Fetching data from the server: 7 seconds
176+
2. Processing the data: 5 seconds
177+
178+
Total time: 7s + 5s = 12s
179+
*/
180+
181+
// function fetchData() {
182+
// console.log('FETCHING DATA FROM THE SERVER ...')
183+
// return new Promise((resolve, reject) => {
184+
// setTimeout(() => {
185+
// console.log('FETCHED DATA SUCCESSFULLY ✅')
186+
// resolve()
187+
// }, 7000)
188+
// })
189+
// }
190+
191+
// function processData() {
192+
// console.log('NOW, PROCESSING DATA ...')
193+
// return new Promise((resolve, reject) => {
194+
// setTimeout(() => {
195+
// console.log('PROCESSED DATA SUCCESSFULLY ✅')
196+
// resolve()
197+
// }, 5000)
198+
// })
199+
// }
200+
201+
// fetchData()
202+
// .then(() => processData())
203+
// .then(() => {})
204+
// .catch(() => console.log('Something went wrong'))
205+
</script>
206+
</body>
207+
</html>

‎JavaScript/Promises2.html‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
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>Promise Chaining</title>
7+
</head>
8+
<body>
9+
<button onclick="placeOrder()">Place order</button>
10+
11+
<script>
12+
/*
13+
# Callback Hell (Pyramid of doom): The structure formed when a callback function is within another callback function and the pattern continues ...
14+
- This is a disadvantage of callbacks
15+
- Hence, the alternative approaches of handling asynchonous code are promises and async-await
16+
17+
- Example: Order tracking app
18+
- Instantly: Order confirmed ✅
19+
- After 2 seconds: Order is being prepared 🍜
20+
- After 10 seconds: Order prepared 🎉
21+
- After 5 seconds: Order handed over to the delivery person 📦
22+
- After 3 seconds: Order is on the way 🚴
23+
- After 8 seconds: Order reached it's destination 📍
24+
- After 4 seconds: Order has been delivered 😋
25+
26+
Total processing time for order: 32 seconds
27+
*/
28+
29+
const orderBeingPrepared = () => new Promise((resolve, reject) => {
30+
setTimeout(() => {
31+
console.log('Order is being prepared 🍜')
32+
resolve()
33+
}, 2000)
34+
})
35+
36+
const orderPrepared = () => new Promise((resolve, reject) => {
37+
setTimeout(() => {
38+
console.log('Order prepared 🎉')
39+
resolve()
40+
}, 10000)
41+
})
42+
43+
const orderHandedOver = () => new Promise((resolve, reject) => {
44+
setTimeout(() => {
45+
console.log('Order handed over to the delivery person 📦')
46+
resolve()
47+
}, 5000)
48+
})
49+
50+
const orderOnTheWay = () => new Promise((resolve, reject) => {
51+
setTimeout(() => {
52+
console.log('Order is on the way 🚴')
53+
resolve()
54+
}, 3000)
55+
})
56+
57+
const orderReachedDestintaion = () => new Promise((resolve, reject) => {
58+
setTimeout(() => {
59+
console.log(`Order reached it's destination 📍`)
60+
resolve()
61+
}, 8000)
62+
})
63+
64+
const orderDelivered = () => new Promise((resolve, reject) => {
65+
setTimeout(() => {
66+
console.log(`Order has been delivered 😋`)
67+
resolve()
68+
}, 4000)
69+
})
70+
71+
const placeOrder = () => {
72+
console.log('Order confirmed ✅')
73+
orderBeingPrepared()
74+
.then(() => orderPrepared())
75+
.then(() => orderHandedOver())
76+
.then(() => orderOnTheWay())
77+
.then(() => orderReachedDestintaion())
78+
.then(() => orderDelivered())
79+
.then(() => console.log('Enjoy your meal ✅'))
80+
.catch(() => console.log('Something went wrong'))
81+
}
82+
83+
84+
85+
86+
87+
/* ---------------------------- */
88+
// const placeOrder = () => {
89+
// console.log('Order confirmed ✅')
90+
// orderBeingPrepared()
91+
// .then(orderPrepared)
92+
// .then(orderHandedOver)
93+
// .then(orderOnTheWay)
94+
// .then(orderReachedDestintaion)
95+
// .then(orderDelivered)
96+
// .then(() => console.log('Enjoy your meal ✅'))
97+
// .catch(() => console.log('Something went wrong'))
98+
// }
99+
</script>
100+
</body>
101+
</html>

0 commit comments

Comments
 (0)