Promise

2 snippets in JavaScript

Also written as Promise.all

JSJavaScript

Promise Basics

JS · Async Programming
syntax
new Promise((resolve, reject) => { ... })
promise.then(onFulfilled, onRejected)
promise.catch(onRejected)
promise.finally(onFinally)
example
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

delay(1000)
  .then(() => console.log("1 second passed"))
  .catch(err => console.error(err))
  .finally(() => console.log("Done"));

Note A Promise is always in one of three states: pending, fulfilled, or rejected. Once settled, it cannot change state.

Promise.all()

JS · Async Programming
syntax
Promise.all([p1, p2, p3])
example
async function loadDashboard(userId) {
  const [profile, posts, notifications] = await Promise.all([
    fetch(`/api/users/${userId}`).then(r => r.json()),
    fetch(`/api/posts?author=${userId}`).then(r => r.json()),
    fetch(`/api/notifications/${userId}`).then(r => r.json()),
  ]);
  return { profile, posts, notifications };
}

Note Runs all promises in parallel and resolves when ALL succeed. Rejects immediately if ANY promise rejects -- other pending promises are not cancelled, just ignored.