Skip to main content
Submitted by admin on 19 November 2023
JavaScript

A promise can be in one of three states:


  1. Pending: Initial state, neither fulfilled nor rejected.
  2. Fulfilled: The operation completed successfully, and the promise has a value.
  3. Rejected: The operation failed, and the promise has a reason for the failure.

Promises have methods such as `then()` and `catch()` which allow you to attach callbacks to handle the fulfillment or rejection of the promise. Here's a basic example:

const myPromise = new Promise((resolve, reject) => {
  // Asynchronous operation, e.g., fetching data from a server
  setTimeout(() => {
    const success = true;
    if (success) {
      resolve("Operation succeeded!"); // Resolve the promise with a value
    } else {
      reject("Operation failed!"); // Reject the promise with a reason
    }
  }, 2000);
});

myPromise.then((value) => {
  console.log(value); // Output: Operation succeeded!
}).catch((reason) => {
  console.error(reason); // Output: Operation failed!
});

Promises are especially useful when working with asynchronous functions like fetching data from a server, reading files, or handling timeouts. They simplify the asynchronous code structure, making it more readable and manageable. Additionally, promises can be chained together using then() to perform multiple asynchronous operations sequentially.