You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
1. Callback Hell: Asynchronous operations in JavaScript can be achieved through callbacks. Whenever there are multiple dependent Asynchronous operations it will result in a lot of nested callbacks. This will cause a 'pyramid of doom' like structure.
58
+
2. Inversion of control: When we give the control of callbacks being called to some other API, this may create a lot of issues. That API may be buggy, may not call our callback and create order as in the above example, may call the payment callback twice etc.
//Promises are used to handle asynchronous operations in a synchronous manner, making it //easier to write and reason about async code. Instead of using callback functions, you can //use the then and catch methods on a Promise to specify what should happen when the Promise //is fulfilled or rejected.
64
68
65
-
66
69
constfetchUser= (username) => {
67
-
returnnewPromise((resolve, reject) => {
68
-
setTimeout(() => {
69
-
console.log("[Now we have the user]");
70
+
returnnewPromise((resolve, reject) => {
71
+
setTimeout(() => {
72
+
console.log("[Now we have the user]");
70
73
71
-
resolve({ username });
72
-
}, 2000);
73
-
});
74
+
resolve({ username });
75
+
}, 2000);
76
+
});
74
77
};
75
78
76
79
constfetchUserPhotos= (username) => {
77
-
returnnewPromise((resolve, reject) => {
78
-
setTimeout(() => {
79
-
console.log(`Now we have the photos for ${username}`);
80
-
resolve(["Photo1", "Photo2"]);
81
-
}, 2000);
82
-
});
80
+
returnnewPromise((resolve, reject) => {
81
+
setTimeout(() => {
82
+
console.log(`Now we have the photos for ${username}`);
83
+
resolve(["Photo1", "Photo2"]);
84
+
}, 2000);
85
+
});
83
86
};
84
87
85
88
constfetchPhotoDetails= (photo) => {
86
-
returnnewPromise((resolve, reject) => {
87
-
setTimeout(() => {
88
-
console.log(`[Now we have the photo details ${photo}]`);
89
-
resolve("details...");
90
-
}, 2000);
91
-
});
89
+
returnnewPromise((resolve, reject) => {
90
+
setTimeout(() => {
91
+
console.log(`[Now we have the photo details ${photo}]`);
92
+
resolve("details...");
93
+
}, 2000);
94
+
});
92
95
};
93
96
94
97
fetchUser("Shubham")
95
-
.then((user) =>fetchUserPhotos(user.username))
96
-
.then((photos) =>fetchPhotoDetails(photos[0]))
97
-
.then((details) =>console.log(`Your photo details are ${details}`));
98
+
.then((user) =>fetchUserPhotos(user.username))
99
+
.then((photos) =>fetchPhotoDetails(photos[0]))
100
+
.then((details) =>console.log(`Your photo details are ${details}`));
0 commit comments