Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Promises: States, Chains, and Reliability

Promises represent future values from asynchronous operations and are the foundation of modern async JavaScript patterns.

Why this matters

Without strong promise handling, async code becomes fragile and hard to maintain.

Promise Lifecycle and Chaining

Every promise starts pending and settles once as fulfilled or rejected.

then returns a new promise, enabling linear chains instead of nested callbacks.

Errors thrown in then blocks travel to nearest catch, enabling centralized handling.

Choosing Promise Combinators

Use Promise.all when every task must succeed.

Use Promise.allSettled when you need results from all tasks regardless of individual failures.

Use Promise.race for first completion and Promise.any for first success.

Code Examples

Basic Promise Chain

function getUser(id) {
  return fetch("https://jsonplaceholder.typicode.com/users/" + id)
    .then((r) => r.json());
}

getUser(1)
  .then((user) => user.email)
  .then((email) => console.log(email))
  .catch((error) => console.error(error.message));

then chain keeps asynchronous flow linear and readable.

allSettled for Partial Success

const tasks = [
  Promise.resolve("A success"),
  Promise.reject(new Error("B failed")),
  Promise.resolve("C success"),
];

Promise.allSettled(tasks).then((result) => console.log(result));

Use allSettled when partial completion is acceptable.

Promise Wrapper for setTimeout

function wait(ms) {
  return new Promise((resolve) => {
    setTimeout(() => resolve("done"), ms);
  });
}

wait(300).then(console.log);

Wrapping callback APIs into promises modernizes async composition.

Common Mistakes and Fixes

Missing return inside then

Return value/promise inside then when next step depends on it.

Ignoring catch handlers

Always handle rejection with catch or try/catch via async/await.

Over-nested then chains

Chain linearly or switch to async/await for readability.

Frequently Asked Questions

Can a promise change state after resolve?

No. Promise state is immutable once settled.

When should I use Promise.all?

Use it when all operations are required and a single failure should fail the complete operation.

What is the purpose of finally?

It runs cleanup logic regardless of success or failure.

Is async/await replacing promises?

No. async/await is syntax built on top of promises.

Related JavaScript Topics