Promises
Overview
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation.
Before Promises (ES6), developers had to use nested callbacks to handle async data, leading to the infamous 'Callback Hell'. Promises flatten this logic by providing .then() (for success) and .catch() (for errors).
A Promise has three states: Pending, Fulfilled, and Rejected.
Syntax
const myPromise = fetch('https://api.github.com/users');
myPromise
.then(response => {
// Runs when the promise is FULFILLED
console.log("Data received!");
})
.catch(error => {
// Runs when the promise is REJECTED
console.log("Network error!");
})
.finally(() => {
// Runs regardless of success or failure
console.log("Request finished.");
});const checkWeather = new Promise((resolve, reject) => {
const isSunny = true;
if (isSunny) {
resolve("It's a beautiful day!"); // Triggers .then()
} else {
reject("It's raining!"); // Triggers .catch()
}
});Common Pitfalls
- Forgetting to
returna new Promise inside a.then()block if you want to chain them. If you just call an async function without returning it, the chain breaks, and the next.then()will fire immediately withundefined.
Interview Questions
1. Pending (initial state). 2. Fulfilled (operation completed successfully). 3. Rejected (operation failed).
Promise.all() used for?It takes an array of Promises and executes them all concurrently. It resolves only when ALL of them succeed, or rejects immediately if ANY of them fail. It is much faster than running independent promises sequentially.
Real-World Example
Fetching user data, and then fetching their specific posts only after the user data arrives (Promise Chaining).
fetchUser()
.then(user => fetchPosts(user.id))
.then(posts => render(posts))
.catch(handleError);Check Your Knowledge
Test your understanding of Promises with these quick questions.