What are Promises?
1. Definition
A Promise is an object in JavaScript that represents the eventual completion or failure of an asynchronous operation and its result.
2. Promise States
- Pending: Initial state
- Fulfilled: Operation completed successfully
- Rejected: Operation failed
3. Key Idea
- Handles asynchronous operations
- Avoids callback hell
- Improves readability
- Supports chaining
4. How it Works
- Create a Promise
- Perform async operation
- Resolve (success) or Reject (error)
- Handle result using .then() and .catch()
5. Example
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Task completed");
} else {
reject("Task failed");
}
});
myPromise
.then(result => console.log(result))
.catch(error => console.log(error));6. Promise Chaining
loginUser(user)
.then(getOrders)
.then(getOrderDetails)
.then(processPayment)
.then(() => console.log("Done"))
.catch(err => console.log(err));7. Advantages
- Avoids callback hell
- Better readability
- Easy error handling
- Supports chaining
8. Disadvantages
- Slightly complex for beginners
- Can still become complex if overused
Interview Points
- Promise represents async result
- Has 3 states: pending, fulfilled, rejected
- Uses .then() and .catch()
- Solves callback hell problem