This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

JavaScript Promises Cheatsheet

A quick reference guide for JavaScript Promises: constructor, chaining, error handling, Promise combinators (all, allSettled, race, any), and async/await.

· Published

A Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

Promise States

A Promise is always in one of three mutually exclusive states:

  1. pending: Initial state, neither fulfilled nor rejected.
  2. fulfilled: Operation completed successfully (resolve(value)).
  3. rejected: Operation failed (reject(error)).

Constructor & Basic Chaining

const loadUser = (id) => {
  return new Promise((resolve, reject) => {
    fetch(`/api/users/${id}`)
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      })
      .then((data) => resolve(data))
      .catch((err) => reject(err));
  });
};

loadUser(42)
  .then((user) => console.log('Loaded:', user.name))
  .catch((err) => console.error('Error:', err.message))
  .finally(() => console.log('Request finished'));

Static Resolvers

// Immediately fulfilled promise
const p1 = Promise.resolve('Immediate value');

// Immediately rejected promise
const p2 = Promise.reject(new Error('Immediate failure'));

Promise Combinators

Method Behavior Fails When
Promise.all([p1, p2]) Waits for all to fulfill Any promise rejects (short-circuits)
Promise.allSettled([p1, p2]) Waits for all to finish (never rejects) Never rejects
Promise.race([p1, p2]) Settles with first settled promise First settled promise rejects
Promise.any([p1, p2]) Fulfills with first fulfilled promise All promises reject (AggregateError)
// Promise.all: Wait for multiple independent requests
const [users, posts] = await Promise.all([
  fetchUsers(),
  fetchPosts()
]);

// Promise.allSettled: Inspect statuses of all requests
const results = await Promise.allSettled([reqA(), reqB()]);
results.forEach((res) => {
  if (res.status === 'fulfilled') console.log('Value:', res.value);
  else console.error('Reason:', res.reason);
});

Async / Await Equivalent

async function getUserData(id) {
  try {
    const res = await fetch(`/api/users/${id}`);
    const data = await res.json();
    return data;
  } catch (err) {
    console.error('Failed to retrieve user:', err);
    throw err;
  }
}

References

Related topics