Labs ICT
โญ Pro Login

Promises

What is a Promise?

A Promise represents a value that may be available now, later, or never. It has three states: pending, fulfilled, or rejected.

const promise = new Promise((resolve, reject) => {
  let success = true;
  if (success) {
    resolve("Operation succeeded");
  } else {
    reject("Operation failed");
  }
});
Try it Yourself โ†’

then, catch, finally

Use .then() for success, .catch() for errors, and .finally() for cleanup after either.

fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error:", error))
  .finally(() => console.log("Request complete"));
Try it Yourself โ†’

Promise.all

Run multiple promises in parallel and wait for all to complete. Rejects immediately if any promise rejects.

const p1 = Promise.resolve(10);
const p2 = Promise.resolve(20);
const p3 = Promise.resolve(30);

Promise.all([p1, p2, p3]).then(values => {
  console.log(values); // [10, 20, 30]
});
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What does a Promise represent?