A Promise is an object representing the eventual completion or failure of an asynchronous operation. Promises replace nested callback pyramids with clean .then(), .catch(), and .finally() chaining.
flowchart TD
Pending["Pending (Initial Unresolved State)"] --> ResolveAttempt{"Operation Result"}
ResolveAttempt -- "resolve(data)" --> Fulfilled["Fulfilled State (Value returned -> .then())"]
ResolveAttempt -- "reject(error)" --> Rejected["Rejected State (Error thrown -> .catch())"]
| Combinator | Behavior | Resolves When | Rejects When |
|---|---|---|---|
Promise.all([p1, p2]) |
Parallel execution | All promises fulfill. | First promise rejects (Short-circuits). |
Promise.allSettled([p1, p2]) |
Parallel inspection | All promises settle (fulfill OR reject). | Never rejects (Returns status array). |
Promise.race([p1, p2]) |
Winner-takes-all | First promise settles (fulfill or reject). | First promise rejects. |
Promise.any([p1, p2]) |
First success wins | First promise fulfills. | All promises reject (AggregateError). |
// Demonstrating Promise creation, chaining, and Promise.allSettled
// 1. Creating a Promise Function
function fetchProductData(productId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (productId <= 0) {
reject(new Error("Invalid Product ID"));
} else {
resolve({ id: productId, name: "Mechanical Keyboard", price: 99.99 });
}
}, 100);
});
}
// 2. Chaining .then(), .catch(), and .finally()
fetchProductData(42)
.then(product => {
console.log(`Product Name: ${product.name}`);
return product.price * 0.9; // Return value passed to next .then()
})
.then(discountedPrice => {
console.log(`Discounted Price: \$${discountedPrice.toFixed(2)}`);
})
.catch(err => {
console.error(`Promise Error: ${err.message}`);
})
.finally(() => {
console.log("Product fetch pipeline finished.");
});
// 3. Parallel Execution with Promise.allSettled
const p1 = fetchProductData(1);
const p2 = fetchProductData(-5); // Will fail
Promise.allSettled([p1, p2]).then(results => {
console.log("
--- Promise.allSettled Results ---");
results.forEach((res, idx) => {
if (res.status === "fulfilled") {
console.log(`Task #${idx + 1} Success:`, res.value);
} else {
console.error(`Task #${idx + 1} Failed: ${res.reason.message}`);
}
});
});
.then() Chains: Ensure callbacks inside .then() return values or Promises so data flows cleanly down the chain.Promise.allSettled() Over Promise.all() for Independent Batch Tasks: Promise.all() aborts immediately if any single promise fails. Use Promise.allSettled() if you want all tasks to run regardless of individual failures..catch(): Unhandled Promise rejections cause UnhandledPromiseRejectionWarning node crashes.What is the difference between Promise.all() and Promise.allSettled() when one promise in the input array rejects?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.