What is a Promise in JS?

_Khojiakbar_ - Jul 7 - - Dev Community

What is a Promise?

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Think of it as a "promise" to deliver a result at some future time.

Key States of a Promise

A promise can be in one of three states:

  1. Pending: The initial state. The promise is neither fulfilled nor rejected.
  2. Fulfilled: The operation completed successfully.
  3. Rejected: The operation failed.

. Basic Structure

Here's the basic structure of creating a promise:

let myPromise = new Promise((resolve, reject) => {
  // Asynchronous operation
  if (/* operation successful */) {
    resolve('Success!');
  } else {
    reject('Failure!');
  }
});
Enter fullscreen mode Exit fullscreen mode

Using Promises

You use .then() to handle a fulfilled promise and .catch() to handle a rejected promise.

myPromise
  .then(result => {
    console.log(result); // 'Success!'
  })
  .catch(error => {
    console.log(error); // 'Failure!'
  });
Enter fullscreen mode Exit fullscreen mode

Funny Example: Ordering Pizza

Imagine you're ordering a pizza. You call the pizzeria (async operation), and they promise to deliver the pizza (Promise).

let orderPizza = new Promise((resolve, reject) => {
  let pizzaReady = true; // Change to false to simulate a failure

  console.log("Ordering pizza...");

  setTimeout(() => {
    if (pizzaReady) {
      resolve("Pizza is here!");
    } else {
      reject("Sorry, we ran out of dough.");
    }
  }, 2000); // Simulate a 2-second wait for pizza
});

orderPizza
  .then(message => {
    console.log(message); // "Pizza is here!"
  })
  .catch(error => {
    console.log(error); // "Sorry, we ran out of dough."
  });
Enter fullscreen mode Exit fullscreen mode

Chaining Promises

You can chain multiple .then() calls. Each .then() returns a new promise.

orderPizza
  .then(message => {
    console.log(message); // "Pizza is here!"
    return "Enjoy your pizza!";
  })
  .then(message => {
    console.log(message); // "Enjoy your pizza!"
  })
  .catch(error => {
    console.log(error); // "Sorry, we ran out of dough."
  });
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player