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+ email : "aditya@example.com"
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 : "guest@example.com" } ;
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"
0 commit comments