Labs ICT
โญ Pro Login

Promises

1 min read | JavaScript Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

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");
  }
});

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"));

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]
});

๐Ÿงช Quick Quiz

What does a Promise represent?