Skip to content

JavaScript Promise API

JavaScript Promise methods for asynchronous programming — combining, racing, resolving, and handling async values.

1 class · 10 methods

Promise

10 methods

Represents the eventual result of an asynchronous operation. Core async primitive in JavaScript (ES6+).

Promise.all(iterable)

Wait for all promises to fulfill. Rejects immediately if any promise rejects (fast-fail). Returns an array of results in input order.

Parameters

NameTypeDescription
iterableIterable<Promise | non-Promise>An iterable of promises (or values treated as already-resolved promises).

Returns

Promise<Array>

Example

javascript
const [user, posts, comments] = await Promise.all([
  fetchUser(1),
  fetchPosts(1),
  fetchComments(1),
]);
// If any fails, the whole thing rejects immediately.
Promise.allSettled(iterable)

Wait for all promises to settle (fulfill or reject). Never rejects — returns an array of { status, value } or { status, reason } objects. Useful when you want all results regardless of failures.

Parameters

NameTypeDescription
iterableIterable<Promise | non-Promise>An iterable of promises.

Returns

Promise<Array<{ status: 'fulfilled', value } | { status: 'rejected', reason }>>

Example

javascript
const results = await Promise.allSettled([
  fetch('/api/a'),
  fetch('/api/b'),
  fetch('/api/c'),
]);
results.forEach(r => {
  if (r.status === 'fulfilled') console.log('OK:', r.value);
  else console.log('Fail:', r.reason);
});
Promise.any(iterable)

Resolve with the first fulfilled promise. Rejects only if ALL promises reject (AggregateError). Useful for 'first successful response' patterns (e.g., racing CDNs).

Parameters

NameTypeDescription
iterableIterable<Promise | non-Promise>An iterable of promises.

Returns

Promise<value>

Example

javascript
// Use the fastest-responding mirror
const fastest = await Promise.any([
  fetch('https://mirror1.example.com/api'),
  fetch('https://mirror2.example.com/api'),
  fetch('https://mirror3.example.com/api'),
]);
// fastest is the response of the first one to succeed.
Promise.race(iterable)

Resolve or reject with the first promise to settle (fulfill OR reject). Useful for implementing timeouts. Unlike any(), a rejection also wins the race.

Parameters

NameTypeDescription
iterableIterable<Promise | non-Promise>An iterable of promises.

Returns

Promise<value>

Example

javascript
// 5-second timeout
function withTimeout(promise, ms) {
  return Promise.race([
    promise,
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error('timeout')), ms)
    ),
  ]);
}
const result = await withTimeout(fetch('/slow-api'), 5000);
Promise.resolve(value)

Create a promise that resolves immediately with the given value. If value is already a promise, it is returned as-is. Useful for converting non-promise values to promises or ensuring consistent async return types.

Parameters

NameTypeDescription
valueanyValue to resolve with. If it's a thenable, follows it.

Returns

Promise<value>

Example

javascript
// Ensure async return type
function getData(sync = false) {
  if (sync) return Promise.resolve(cachedData);
  return fetch('/api/data').then(r => r.json());
}
// Awaiting Promise.resolve(value) is a microtask:
await Promise.resolve();  // yields to the event loop
Promise.reject(reason)

Create a promise that rejects immediately with the given reason. Mostly used for testing or for explicit error signaling in promise chains.

Parameters

NameTypeDescription
reasonanyRejection reason (usually an Error object).

Returns

Promise<never>

Example

javascript
// Validate before continuing
function requireAuth(user) {
  if (!user) return Promise.reject(new Error('Unauthorized'));
  return Promise.resolve(user);
}
try {
  await requireAuth(null);
} catch (e) {
  console.error(e.message);  // 'Unauthorized'
}
Promise.try(executor)since ES2025

ES2025. Wrap a synchronous or asynchronous function call as a promise. Combines try/catch semantics with promise chaining — eliminates the dual try/catch + .catch() pattern. Falls back gracefully if not available.

Parameters

NameTypeDescription
executor() => value | PromiseFunction to execute (sync or async).

Returns

Promise<value>

Example

javascript
// Old way: dual try/catch + .catch
async function load() {
  try {
    const data = JSON.parse(raw);  // sync throw
    return await fetch('/save', { body: JSON.stringify(data) });
  } catch (e) {
    handle(e);  // catches both
  }
}
// New way: Promise.try handles both
Promise.try(() => JSON.parse(raw))
  .then(data => fetch('/save', { body: JSON.stringify(data) }))
  .catch(handle);  // catches both sync and async errors
promise.then(onFulfilled, onRejected?)

Register fulfillment and (optionally) rejection handlers. Returns a new promise, enabling chaining. If a handler returns a value, the new promise resolves with it; if it returns a promise, the new promise adopts its state.

Parameters

NameTypeDescription
onFulfilled(value) => result | PromiseCallback run when the promise fulfills.
onRejected(reason) => result | PromiseOptional. Callback run when the promise rejects (acts like catch).

Returns

Promise<result>

Example

javascript
// Chaining with value transformation
fetch('/api/user/1')
  .then(r => r.json())           // Promise resolves with parsed JSON
  .then(user => user.name)       // Resolves with the name string
  .then(name => `Hello, ${name}`)
  .then(greeting => console.log(greeting));
promise.catch(onRejected)

Register a rejection handler. Returns a new promise. If onRejected returns a value (or doesn't throw), the new promise RESOLVES (recovery), so catch can be used to recover from errors mid-chain.

Parameters

NameTypeDescription
onRejected(reason) => result | PromiseCallback run when the promise rejects.

Returns

Promise<result>

Example

javascript
// Recovery: catch returns a value, so the chain continues
fetch('/api/primary')
  .catch(() => fetch('/api/fallback'))  // try fallback
  .then(r => r.json())
  .then(data => render(data));
// Without recovery (just log):
promise.catch(err => console.error('failed:', err));
promise.finally(onFinally)

Register a handler that runs regardless of fulfillment or rejection. The returned promise mirrors the original's state. onFinally cannot inspect the value or reason, and any value it returns is ignored. Useful for cleanup.

Parameters

NameTypeDescription
onFinally() => voidCallback run when the promise settles.

Returns

Promise<value>

Example

javascript
// Show/hide loading spinner regardless of outcome
button.disabled = true;
showSpinner();
fetch('/api/save', { method: 'POST', body: data })
  .then(r => showToast('Saved!'))
  .catch(e => showToast('Error: ' + e.message))
  .finally(() => {
    button.disabled = false;
    hideSpinner();
  });