What is a Promise?
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation. It's a way to handle asynchronous code without callback hell.
💡 Key insight
A Promise is like a receipt at a restaurant. You get it immediately, but the food (the result) comes later. The receipt can be fulfilled (food arrives) or rejected (order canceled).
Promise States
- Pending: Initial state, not yet fulfilled or rejected
- Fulfilled: Operation completed successfully
- Rejected: Operation failed
Creating a Promise
const promise = new Promise((resolve, reject) => {
// Asynchronous operation
if (success) {
resolve(result); // Fulfilled
} else {
reject(error); // Rejected
}
});
Using Promises
// With .then() and .catch()
promise
.then(result => console.log(result))
.catch(error => console.error(error));
// With async/await (covered next lesson)
async function handlePromise() {
try {
const result = await promise;
console.log(result);
} catch (error) {
console.error(error);
}
}
Promise Chaining
Promises can be chained to run sequential async operations.
fetchUser()
.then(user => fetchProfile(user.id))
.then(profile => console.log(profile))
.catch(error => console.error(error));
Promise Methods
Promise.all()— waits for all promises to resolvePromise.race()— resolves with the first promise to settlePromise.allSettled()— waits for all promises to settlePromise.resolve()— returns a resolved promisePromise.reject()— returns a rejected promise
Common Mistakes
- Forgetting to return a promise in a chain (breaks the chain)
- Not handling errors with
.catch() - Creating promises that don't actually resolve or reject
- Using
Promise.all()when a single failure should not stop everything
Quick Quiz
1. What are the three states of a Promise?
2. Which method is used to handle a rejected promise?
3. What does Promise.all() do?
4. What happens if you don't call resolve() or reject()?
Summary
- Promises represent asynchronous operations
- States: Pending, Fulfilled, Rejected
- Use
.then()for success,.catch()for errors - Chain promises for sequential operations
Promise.all()waits for all promises- Always handle errors with
.catch()
