DEV Community

Bhuvana Sri R
Bhuvana Sri R

Posted on

Promise in JavaScript

Promise

A Promise in JavaScript is an object that represents the eventual completion (success) or failure of an asynchronous operation and its resulting value.

A Promise has three states:

  • Pending – the operation is still going on.
  • Fulfilled – the operation completed successfully (resolve).
  • Rejected – the operation failed (reject).

Example :

let promise = new Promise((resolve, reject) => {
  // Do some task (like fetching data)

  let success = true; 

  if (success) {
    resolve("Task completed successfully!");
  } else {
    reject("Task failed!");
  }
});

// Using .then() and .catch()
promise
  .then(result => {
    console.log("Success:", result);
  })
  .catch(error => {
    console.log("Error:", error);
  });

Enter fullscreen mode Exit fullscreen mode

Example :

function getData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let dataFetched = true;

      if (dataFetched) {
        resolve("Data received!");
      } else {
        reject("Failed to fetch data.");
      }
    }, 2000);
  });
}

getData()
  .then(response => console.log(response))  // Success
  .catch(error => console.log(error));      // Failure

Enter fullscreen mode Exit fullscreen mode

Promise Methods :

  1. - .then() → runs when promise is resolved.
  2. - .catch() → runs when promise is rejected.
  3. - .finally() → runs always (success or failure).
  4. - Promise.all([p1, p2, ...]) → waits for all promises.
  5. - Promise.race([p1, p2, ...]) → returns the first settled promise.

Top comments (0)