JavaScript
Handle asynchronous tasks cleanly with Promise states, chaining, error handling, and combinator methods.
Promises in Simple Terms
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. It replaces messy nested callback functions ("Callback Hell") with clean, chainable logic.
When you order a meal at a fast-food counter, the cashier gives you a vibrating buzzer token:
- Pending: You hold the token while the chef cooks. You don't have food yet, but you have a guarantee.
- Fulfilled (Resolved): The buzzer beeps green! You pick up your meal at the counter (
.then()). - Rejected: The buzzer beeps red because the ingredients ran out (
.catch()). - Settled: Once resolved or rejected, the promise is done and its state never changes.
Creating & Consuming a Promise
Use new Promise((resolve, reject) => { ... }) to wrap any async operation:
function fetchScore(playerName) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (playerName) resolve({ player: playerName, score: 98 });
else reject(new Error("Missing player name!"));
}, 100);
});
}
fetchScore("Aman")
.then(data => {
console.log("Score received:", data.player, "scored", data.score);
return data.score + 10;
})
.then(bonusScore => console.log("With bonus points:", bonusScore))
.catch(err => console.error("Fetch failed:", err.message))
.finally(() => console.log("Promise settled completely."));
Score received: Aman scored 98 With bonus points: 108 Promise settled completely.
The 4 Essential Promise Combinators
When dealing with multiple promises concurrently, JavaScript provides 4 battle-tested static methods:
Promise.all()
All or Nothing: Resolves when ALL promises resolve; fails fast immediately if ANY single promise rejects.
Promise.allSettled()
Never Fails: Waits for ALL promises to finish regardless of success or failure. Returns status objects.
Promise.race()
Fastest Finisher: Settles as soon as the FIRST promise resolves OR rejects.
Promise.any()
First Success: Resolves as soon as the FIRST promise resolves. Ignores rejections unless all reject.
Hands-On Practice: Build a Sleep Delay Helper
Implement a function delay(ms) that returns a Promise which resolves with the message "Done waiting [ms]ms" after ms milliseconds.