Topic 25 of 37
Promises & Chaining
Overview
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. It solves 'Callback Hell' (deeply nested callbacks) by allowing you to chain operations elegantly. A Promise is always in one of three states: Pending, Fulfilled, or Rejected.
Syntax
.then() handles fulfillment, .catch() handles rejection anywhere in the chain, and .finally() runs regardless of the outcome.
Consuming a Promise
javascript
fetch('https://api.github.com/users/octocat')
.then(response => {
if (!response.ok) throw new Error("Failed to fetch");
return response.json();
})
.then(data => console.log(data.login))
.catch(error => console.error("Error:", error.message))
.finally(() => console.log("Done fetching"));Creating a Custom Promise
javascript
const delay = (ms) => new Promise((resolve, reject) => {
if (ms < 0) reject("Delay must be positive");
setTimeout(() => resolve(`Waited ${ms}ms`), ms);
});
delay(1000).then(console.log);Common Pitfalls
- Forgetting to return a Promise inside a .then() block breaks the chain.
- Promise.all() fails fast: if ONE promise rejects, the entire Promise.all() rejects immediately.
Interview Tips
- Know how to wrap a legacy callback-based function (like setTimeout or fs.readFile) into a Promise.
Real-World Example
Parallel execution of independent promises for speed.
example
javascript
// Fetching user details and posts simultaneously
Promise.all([
fetch('/api/user/1').then(res => res.json()),
fetch('/api/posts?userId=1').then(res => res.json())
]).then(([user, posts]) => {
renderProfile(user, posts);
});