Script Valley
JavaScript in the Browser: DOM, Events & APIs
Asynchronous JavaScript and the Fetch APILesson 4.2

JavaScript Promises: then, catch, and Promise.all

Promise constructor, resolve, reject, then, catch, finally, Promise.all, Promise.allSettled, chaining, error propagation

Promises

A Promise represents a value that will be available in the future. It has three states: pending, fulfilled, or rejected.

function fetchUser(id) {
  return new Promise((resolve, reject) => {
    if (!id) reject(new Error('ID required'));
    setTimeout(() => resolve({ id, name: 'Alice' }), 500);
  });
}

fetchUser(1)
  .then(user => console.log(user.name))
  .catch(err => console.error(err.message))
  .finally(() => console.log('Done'));

Chaining

Each .then() returns a new Promise, enabling sequential async steps without nesting.

fetchUser(1)
  .then(user => fetchPosts(user.id))
  .then(posts => renderPosts(posts))
  .catch(err => showError(err));

Promise.all โ€” Parallel Requests

const [users, posts] = await Promise.all([
  fetch('/api/users').then(r => r.json()),
  fetch('/api/posts').then(r => r.json())
]);
// Both requests run in parallel

Promise.allSettled returns results for all promises even if some reject โ€” useful when partial failure is acceptable.

Up next

async/await: writing asynchronous code that reads like synchronous

Sign in to track progress

JavaScript Promises: then, catch, and Promise.all โ€” Asynchronous JavaScript and the Fetch API โ€” JavaScript in the Browser: DOM, Events & APIs โ€” Script Valley โ€” Script Valley