Because JavaScript executes in a single-threaded runtime environment, long-running operations (network requests, disk I/O, timers) cannot block the thread without freezing the entire browser or server.
While callbacks were the original solution for non-blocking code, deeply nested callbacks created Callback Hell (the "Pyramid of Doom"). Promises replaced this by introducing structured, flat async pipelines based on a simple mental model:
$$\text{From: “What runs inside what?”} \longrightarrow \text{To: “What happens next?”}$$
1. Promise Basics: The Three States & The Executor
A Promise has exactly three states:
Pending: The initial state; the asynchronous operation is still executing.Fulfilled: The operation succeeded;resolve(value)was called.Rejected: The operation failed;reject(error)was called.
The Executor Function
When creating a new Promise((resolve, reject) => ...), the executor function runs immediately and synchronously. Calling resolve or reject settles the promise permanently; subsequent calls are silently ignored.
// Creating a Promise with the Executor function
const fetchUserData = new Promise((resolve, reject) => {
const networkSuccess = true;
// Asynchronous operation (e.g. API request simulation)
setTimeout(() => {
if (networkSuccess) {
resolve({ id: 1, name: "Ali", role: "admin" });
} else {
reject(new Error("Network connection failed"));
}
}, 100);
});
// Consuming with .then(), .catch(), and .finally()
fetchUserData
.then(user => {
console.log("1. User fetched:", user.name);
return user.role; // Passes role to the next .then()
})
.then(role => {
console.log("2. Role is:", role);
})
.catch(err => {
console.error("Error caught:", err.message);
})
.finally(() => {
console.log("3. Cleanup: spinner stopped");
});2. Consuming Promises: .then(), .catch(), .finally()
.then(onFulfilled): Executes when the Promise resolves. If you return a value, the next.then()receives it; if you return another Promise, JavaScript waits for it automatically..catch(onRejected): Centralized error boundary for the entire preceding chain..finally(onFinally): Always runs upon settlement for cleanup. Receives no arguments and does not modify the settled value.
3. Error Propagation in Promise Chains
Unlike manual callback trees where each step requires manual error checking, Promises feature automatic rejection propagation:
If an error is thrown or a promise rejects anywhere in a .then() chain, execution immediately skips all subsequent .then() blocks and jumps directly to the nearest .catch().
function step1() { return Promise.resolve("Data 1"); }
function step2() { throw new Error("Step 2 failed!"); }
function step3() { return Promise.resolve("Data 3"); }
// Error skips step3 and jumps directly to .catch()
step1()
.then(data => {
console.log("Step 1 done:", data);
return step2();
})
.then(data => {
console.log("Step 3 done:", data); // SKIPPED!
})
.catch(err => {
console.log("Catch handled:", err.message); // Handles Step 2 error!
})
.then(() => {
console.log("Chain can still continue after .catch()");
});4. The 4 Promise Combinators
When managing multiple concurrent asynchronous operations, JavaScript provides four specialized combinators:
Promise.all()(All-or-Nothing): Waits for all to fulfill. If any promise rejects, it rejects immediately with that error.Promise.allSettled()(Full Visibility): Waits for all to finish, whether fulfilled or rejected. Never rejects.Promise.race()(Fastest Settles): Resolves or rejects as soon as the first promise settles.Promise.any()(First Success): Resolves as soon as the first promise fulfills. Rejects only if all fail (yielding anAggregateError).
const fastSuccess = Promise.resolve("Fast (10ms)");
const slowSuccess = new Promise(r => setTimeout(() => r("Slow (200ms)"), 200));
const fastFail = Promise.reject(new Error("Fast Failure"));
// 1. Promise.all -> All-or-nothing (Fails fast if any promise rejects)
Promise.all([fastSuccess, slowSuccess])
.then(res => console.log("Promise.all:", res)); // ["Fast (10ms)", "Slow (200ms)"]
// 2. Promise.allSettled -> Waits for all, NEVER rejects
Promise.allSettled([fastSuccess, fastFail])
.then(res => console.log("Promise.allSettled:", res));
// [{ status: "fulfilled", value: "Fast (10ms)" }, { status: "rejected", reason: Error }]
// 3. Promise.race -> First to settle wins (fulfilled or rejected)
Promise.race([fastSuccess, slowSuccess])
.then(winner => console.log("Promise.race winner:", winner)); // "Fast (10ms)"
// 4. Promise.any -> First SUCCESS wins (ignores errors unless ALL fail)
Promise.any([fastFail, slowSuccess])
.then(firstSuccess => console.log("Promise.any:", firstSuccess)); // "Slow (200ms)"Combinator | Success Condition | Failure Condition | Settled Value Format | Primary Use Case |
|---|---|---|---|---|
Promise.all() | ALL promises fulfill | ANY promise rejects (fails fast) | Array of values [val1, val2] | Dependent parallel tasks where all are required |
Promise.allSettled() | Always fulfills (all complete) | Never rejects | Array of objects [{status, value/reason}] | Independent tasks where partial success is acceptable |
Promise.race() | First promise fulfills | First promise rejects | Single value or error of the fastest | Request timeouts, fastest mirror response |
Promise.any() | First promise fulfills | ALL promises reject (AggregateError) | Single value of first successful task | Redundant endpoints, fallback service providers |
Think it throughActivity 1: What is the exact console output of this Promise chain?
Promise.resolve(1)
.then(x => x + 1)
.then(x => { throw new Error('Failed at ' + x); })
.catch(err => 10)
.then(x => x * 2)
.then(console.log);
Output: 20
Explanation:
- Resolves with
1$\rightarrow$ next.then()returns2. - Second
.then()throwsError('Failed at 2')$\rightarrow$ skips down to.catch(). - The
.catch()intercepts the error and returns a replacement value10. - Returning
10fulfills the chain! The subsequent.then()receives10, multiplies by 2, and logs20.
Think it throughActivity 2: Predict how Promise.all and Promise.any behave with mixed rejections:
const p1 = Promise.reject('Error A');
const p2 = Promise.resolve('Success B');
Promise.all([p1, p2]).catch(console.log);
Promise.any([p1, p2]).then(console.log);
Output:
Error A (from Promise.all)
Success B (from Promise.any)
Why?
Promise.allrequires all to succeed and fails immediately onp1.Promise.anyignoresp1's rejection and waits for the first fulfillment, resolving withp2.