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
//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.
60
58
61
59
//A Promise starts in the pending state, and it can either be fulfilled with a value or //rejected with a reason (error). Once a Promise is fulfilled or rejected, it is considered //settled, and it cannot be changed anymore.
62
60
63
61
//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
62
63
+
```js{
64
+
// Let's say we have a shopping cart
65
+
const cart = ['shoes','pants','shirt'];
66
+
67
+
// If we had to implement a series of operations
68
+
// let's say we have a function to,
69
+
// 1. Create an order which will return a orderID
70
+
// 2. Proceed to payment with orderId and return payment info.
71
+
// 3. Show order summary with payment info
72
+
73
+
createOrder(cart,(orderID)=>{
74
+
proceedToPayment(orderID,(paymentInfo)=>{
75
+
showOrderSummary(paymentInfo,()=>{
76
+
displayOrderSummary();
77
+
})
78
+
}
79
+
})
80
+
// In the above code we see the call back hell or
81
+
// also known as Pyramid of doom
82
+
83
+
// We can write the same code using promises
84
+
createOrder(cart)
85
+
.then((orderId)=>{
86
+
return proceedToPayment(orderId)
87
+
})
88
+
.then((paymentInfo)=>{
89
+
return showOrderSummary(paymentInfo)
90
+
})
91
+
.then(()=>{
92
+
displayOrderSummary();// not returning anything because we are just displaying
93
+
})
94
+
95
+
// why do we use promises ?
96
+
// 1. To avoid Inversion of Control [Not calling the fuction over another function]
97
+
// 2. To avoid Call Back hell and have better control of our code
98
+
```
65
99
100
+
```js
66
101
constfetchUser= (username) => {
67
102
returnnewPromise((resolve, reject) => {
68
103
setTimeout(() => {
@@ -96,4 +131,3 @@ fetchUser("Shubham")
96
131
.then((photos) =>fetchPhotoDetails(photos[0]))
97
132
.then((details) =>console.log(`Your photo details are ${details}`));
0 commit comments