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 >
0 commit comments