CPCODELAB
JavaScript

Promises

11 min read

Promises

A Promise represents a value that will be available in the future. It can be in one of three states: pending, fulfilled (resolved), or rejected. Promises replaced the old callback pattern and make async code far more readable.

javascript
// Creating a Promise
const delay = (ms) => new Promise((resolve, reject) => {
  if (ms < 0) reject(new Error("Negative delay"));
  setTimeout(() => resolve("Done after " + ms + "ms"), ms);
});

// Consuming with .then / .catch / .finally
delay(1000)
  .then(msg => console.log(msg))   // "Done after 1000ms"
  .catch(err => console.error(err))
  .finally(() => console.log("always runs"));

Promise Combinators

javascript
// All must resolve — rejects if any rejects
Promise.all([delay(100), delay(200)])
  .then(([a, b]) => console.log(a, b));

// Resolves/rejects as soon as the first settles
Promise.race([delay(100), delay(500)])
  .then(result => console.log(result)); // from 100ms promise

// Waits for all to settle (never rejects)
Promise.allSettled([delay(100), delay(-1)])
  .then(results => results.forEach(r => console.log(r.status)));

// First to RESOLVE (ignores rejections)
Promise.any([delay(-1), delay(200)])
  .then(result => console.log(result));

Use Promise.all when tasks are independent and all must succeed. Use Promise.allSettled when you need results from all tasks regardless of individual failures — common when fetching from multiple APIs.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises