JavaScript is single-threaded, meaning it can only do one thing at a time. But what if you need to fetch data from an API, read a file, or wait for a timer without freezing your app?
This is where promises come in.
🧠 What Problem Do Promises Solve?
Before promises, we used callbacks for async tasks:
```js id="cb1"
fetchData(function(data) {
processData(data, function(result) {
console.log(result);
});
});
❌ Callback hell → hard to read, hard to maintain
Promises simplify this by representing a **future value**:
> A promise is like a placeholder for a value that **may not be available yet**.
---
## ⏳ Promise States
A promise can be in **three states**:
1. **Pending** – initial state, waiting for the result
2. **Fulfilled** – operation succeeded, value available
3. **Rejected** – operation failed, error available
```id="viz1"
Pending → Fulfilled or Rejected
⚙️ Basic Promise Lifecycle
```js id="promise1"
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Task completed");
} else {
reject("Task failed");
}
});
promise
.then(result => console.log(result)) // handles success
.catch(error => console.log(error)); // handles failure
### Output if success = true:
```plaintext
Task completed
Output if success = false:
Task failed
🔄 Promise Chaining
Promises can be chained to run multiple async tasks sequentially:
```js id="chain1"
fetchData()
.then(data => processData(data))
.then(result => console.log(result))
.catch(err => console.error(err));
✔ Cleaner than nested callbacks
✔ Easier to read and maintain
---
## 📊 Callback vs Promise
| Feature | Callback | Promise |
| -------------- | ------------ | -------------- |
| Readability | Low (nested) | High (linear) |
| Error handling | Hard | Easy (`catch`) |
| Async flow | Nested | Chained |
| Future value | No | Yes |
---
## 🛠️ Real-World Example
```js id="real1"
function fetchUser(userId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (userId === 1) {
resolve({ id: 1, name: "Rahul" });
} else {
reject("User not found");
}
}, 1000);
});
}
fetchUser(1)
.then(user => console.log(user.name)) // Rahul
.catch(err => console.log(err));
🧩 Visualizing Promise Lifecycle
Promise created → pending
↓
(resolve) fulfilled → .then runs
(reject) rejected → .catch runs
🧠 Key Takeaways
- Promises represent a value in the future
- They prevent callback hell
-
.then()handles success,.catch()handles errors - Can be chained for sequential async operations
🚀 Final Thoughts
Promises are the foundation of modern asynchronous JavaScript. Once you master them, you’ll be ready for:
- Async/await syntax
- Complex async workflows
- Clean, readable, maintainable code
Top comments (0)