DEV Community

_Khojiakbar_
_Khojiakbar_

Posted on

2

What is a Promise in JS?

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

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay