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.

Frequently asked questions

How does JavaScript handle promise?
JavaScript covers this with 2 copy-ready snippets on this page. The "Promise Basics" snippet in JavaScript uses `new Promise((resolve, reject) => { ... })`.
Which code does the JavaScript example use?
The "Promise Basics" snippet uses `new Promise((resolve, reject) => { ... })`, from the Async Programming section of the JavaScript cheat sheet.
What other JavaScript snippets are shown for "promise"?
Besides "Promise Basics", this page also shows "Promise.all()".
Is there anything to watch out for?
Yes. For "Promise Basics": A Promise is always in one of three states: pending, fulfilled, or rejected. Once settled, it cannot change state.