HomeJAVASCRIPTWhat is a promise?

What is a promise?

In JavaScript, a Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

Think of it like a “placeholder” for a value that will be available in the future (like a pending online order—you don’t have it now, but you’ll get it later, or it might fail).


States of a Promise

A Promise can be in one of three states:

  1. Pending → Initial state, neither fulfilled nor rejected.
  2. Fulfilled → Operation completed successfully, and the promise has a result.
  3. Rejected → Operation failed, and the promise has a reason (error).

Syntax

let promise = new Promise((resolve, reject) => {
  // async operation
  let success = true;
  
  if (success) {
    resolve("Task completed successfully!");
  } else {
    reject("Something went wrong.");
  }
});

Consuming a Promise

You handle the result with .then(), .catch(), and .finally():

promise
  .then(result => {
    console.log(result); // if resolved
  })
  .catch(error => {
    console.log(error); // if rejected
  })
  .finally(() => {
    console.log("Promise finished (success or failure).");
  });

Key Points about Promises:

  • They simplify handling of asynchronous tasks (like API calls, file reading, setTimeout).
  • They help avoid callback hell (deeply nested callbacks).
  • They are chainable (.then().then().catch()).
  • Often used with async/await for cleaner code.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *