← Back to libraryQuestion 136 of 468
🟨JavaScriptIntermediate

Promises

📌 Definition:

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. It has three states: pending, fulfilled (resolved), or rejected, and can only settle once.

📖 Detailed Explanation:

Promises solve callback hell by making async flows chainable and composable. A promise starts pending; calling resolve(value) fulfills it and triggers .then(); calling reject(error) rejects it and triggers .catch(). .then() returns a NEW promise, enabling chaining, and a value returned from a .then callback becomes the input to the next .then. Errors propagate down the chain to the nearest .catch, and .finally() runs regardless of outcome. Combinators help coordinate multiple promises: Promise.all (waits for all, fails fast on any rejection), Promise.allSettled (waits for all, never short-circuits), Promise.race (first to settle), and Promise.any (first to fulfill).

🔑 Key Points:
  • States: pending → fulfilled or rejected (settles once)
  • .then chains and transforms; .catch handles errors; .finally always runs
  • Promise.all fails fast; Promise.allSettled reports every result
  • Returning a value/promise from .then feeds the next .then
🌍 Real-World Example:

Fetching test data from three API endpoints in parallel: Promise.all([fetchUser(), fetchOrders(), fetchProducts()]).then(([user, orders, products]) => ...). All three run concurrently and you proceed only when all resolve — far faster than awaiting them one by one.

🎯 Scenario-Based Interview Question:

You need to call 5 independent APIs and continue only after ALL finish, but you also need to know which ones failed. Which Promise combinator do you use and why?