Skip to content

Commit 8949702

Browse files
Added Promises, including creation, chaining, error handling, and common pitfalls.
1 parent 6528856 commit 8949702

2 files changed

Lines changed: 484 additions & 0 deletions

File tree

24_Promises.md

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
# Chapter 24: Promises
2+
3+
## 🎯 What is a Promise?
4+
5+
- **Definition**: A promise is an object representing the **eventual completion (or failure)** of an asynchronous operation. Promises are used to handle async operations in JavaScript.
6+
- **Key Characteristics**:
7+
- Placeholder for a value not yet available (future value).
8+
- Container that gets populated when async operation completes.
9+
- Immutable once resolved (cannot be modified after settlement).
10+
11+
## 🔍 Why Promises?
12+
13+
**BEFORE PROMISES:**
14+
15+
```javascript
16+
const cart = ["Shoe", "Jean", "Pen"];
17+
18+
createOrder(cart);
19+
20+
proceedToPayemnt(OrderId);
21+
```
22+
23+
Now we have a cart and two APIs. `createOrder()` will create the order and return `orderId` to us. And another api `proceedToPayment()` api will take the `orderId` and will take us to payment page.
24+
25+
Now these two APIs are asynchronous in nature. We don't know how much time it will take. And they are dependent on each other.
26+
27+
**WITH THE HELP OF CALLBACKS:**
28+
29+
```javascript
30+
// Callback Hell Example
31+
32+
const cart = ["Shoe", "Jean", "Pen"];
33+
34+
createOrder(cart, function (orderId) {
35+
proceedToPayment(orderId, function (paymentInfo) {
36+
showOrderSummary(paymentInfo, function () {
37+
updateWalletBalance();
38+
});
39+
});
40+
}); // Here we are passing the callback function to another function
41+
```
42+
43+
This is how we used to handle async operation with the help of callbacks.
44+
But the major issue with it is `inversion of control`.
45+
46+
**USING PROMISES:**
47+
48+
We can assume promise as an empty object with some data value in it. And this data value will hold whatever the function will return.
49+
50+
`{data: undefined}`
51+
52+
And after some time when the details are available, they are filled in the data value object at later point of time.
53+
54+
```javascript
55+
const cart = ["Shoe", "Jean", "Pen"];
56+
57+
const promise = api.createOrder(cart);
58+
59+
promise.then(function (orderId) {
60+
api.proceedToPayemnt(orderId);
61+
}); // Here we are attaching the callback function to a promise object
62+
```
63+
64+
---
65+
66+
**Chaining Of Promises:**
67+
68+
```javascript
69+
// Promise Chaining
70+
71+
const cart = ["Shoe", "Jean", "Pen"];
72+
73+
createOrder(cart)
74+
.then(function (orderId) {
75+
return proceedToPayemnt(orderId);
76+
})
77+
.then(function (paymentInfo) {
78+
return showOrderSummary(paymentInfo);
79+
})
80+
.then(function (paymentInfo) {
81+
return updateWalletBalance(paymentInfo);
82+
});
83+
84+
// OR: With arrow function:
85+
86+
createOrder(cart)
87+
.then((orderId) => proceedToPayemnt(orderId))
88+
.then((paymentInfo) => showOrderSummary(paymentInfo))
89+
.then((paymentInfo) => updateWalletBalance(paymentInfo));
90+
```
91+
92+
### Eliminates Inversion of Control:
93+
94+
- With callbacks, we surrender control to external functions.
95+
96+
- With promises, we attach callbacks to promise objects (control remains with us).
97+
98+
### Promise States
99+
100+
| State | Description |
101+
| ----------- | -------------------------------------- |
102+
| `pending` | Initial state (not fulfilled/rejected) |
103+
| `fulfilled` | Operation completed successfully |
104+
| `rejected` | Operation failed |
105+
106+
### Promise Object Structure
107+
108+
```javascript
109+
{
110+
[[Prototype]]: Promise,
111+
[[PromiseState]]: "pending" | "fulfilled" | "rejected",
112+
[[PromiseResult]]: undefined | value | error
113+
}
114+
```
115+
116+
### Key Features
117+
118+
1. Guarantees:
119+
120+
- Callback will be called exactly once
121+
- State transitions are permanent (cannot change after settlement)
122+
123+
2. Error Handling:
124+
125+
- Use `.catch()` or second argument in `.then()`
126+
127+
```javascript
128+
fetchAPI()
129+
.then((data) => process(data))
130+
.catch((err) => handleError(err));
131+
```
132+
133+
3. Chaining:
134+
135+
- Must return values/promises in `.then()` for proper data flow:
136+
137+
```javascript
138+
139+
createOrder(cart)
140+
.then(orderId => {
141+
return proceedToPayment(orderId); // ← Crucial return
142+
})
143+
.then(paymentInfo => ...)
144+
```
145+
146+
### Interview Answers
147+
148+
1. **"What is a Promise?"**
149+
150+
- _"A promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation, serving as a placeholder for the operation's future result."_
151+
152+
2. **"Why use Promises?"**
153+
154+
- Avoid callback hell → Flat, readable code via chaining
155+
156+
- Better control flow → Attach handlers instead of passing callbacks
157+
158+
- Built-in error propagation → Single .catch() for entire chain
159+
160+
- Immutability → Resolved promises can't change state
161+
162+
### ⚠️ Common Pitfalls
163+
164+
1. Forgetting to return in promise chains
165+
2. Not handling errors (uncaught promise rejections)
166+
3. Assuming promises are synchronous (they're always async)
167+
168+
---
169+
170+
<br><br>
171+
172+
<p align="left">
173+
<a href="./23_CallBack_Hell.md"><b>‹ GO TO PREVIOUS</b></a>
174+
</p>
175+
176+
<p align="right">
177+
<a href="./25_Creating_A_Promise_Chaining_And_Error_Handling.md"><b>GO TO NEXT ›</b></a>
178+
</p>
179+
180+
---

0 commit comments

Comments
 (0)