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.
59
+
55
60
#### Promises
56
61
57
62
//In JavaScript, a Promise is an object that represents the result of an asynchronous //operation. A Promise can be in one of three states: pending, fulfilled, or rejected.
@@ -99,35 +104,35 @@ createOrder(cart)
99
104
100
105
```js
101
106
constfetchUser= (username) => {
102
-
returnnewPromise((resolve, reject) => {
103
-
setTimeout(() => {
104
-
console.log("[Now we have the user]");
107
+
returnnewPromise((resolve, reject) => {
108
+
setTimeout(() => {
109
+
console.log("[Now we have the user]");
105
110
106
-
resolve({ username });
107
-
}, 2000);
108
-
});
111
+
resolve({ username });
112
+
}, 2000);
113
+
});
109
114
};
110
115
111
116
constfetchUserPhotos= (username) => {
112
-
returnnewPromise((resolve, reject) => {
113
-
setTimeout(() => {
114
-
console.log(`Now we have the photos for ${username}`);
115
-
resolve(["Photo1", "Photo2"]);
116
-
}, 2000);
117
-
});
117
+
returnnewPromise((resolve, reject) => {
118
+
setTimeout(() => {
119
+
console.log(`Now we have the photos for ${username}`);
120
+
resolve(["Photo1", "Photo2"]);
121
+
}, 2000);
122
+
});
118
123
};
119
124
120
125
constfetchPhotoDetails= (photo) => {
121
-
returnnewPromise((resolve, reject) => {
122
-
setTimeout(() => {
123
-
console.log(`[Now we have the photo details ${photo}]`);
124
-
resolve("details...");
125
-
}, 2000);
126
-
});
126
+
returnnewPromise((resolve, reject) => {
127
+
setTimeout(() => {
128
+
console.log(`[Now we have the photo details ${photo}]`);
129
+
resolve("details...");
130
+
}, 2000);
131
+
});
127
132
};
128
133
129
134
fetchUser("Shubham")
130
-
.then((user) =>fetchUserPhotos(user.username))
131
-
.then((photos) =>fetchPhotoDetails(photos[0]))
132
-
.then((details) =>console.log(`Your photo details are ${details}`));
135
+
.then((user) =>fetchUserPhotos(user.username))
136
+
.then((photos) =>fetchPhotoDetails(photos[0]))
137
+
.then((details) =>console.log(`Your photo details are ${details}`));
0 commit comments