D DevBrainBox

JavaScript Promise

JS

What is a Promise?

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

It acts like a placeholder for a future value, allowing you to write asynchronous code in a cleaner way than using nested callbacks.

Promise States

A Promise has 3 states:

    1. Pending – initial state, neither fulfilled nor rejected.
    1. Fulfilled – the operation completed successfully, with a result value.
    1. Rejected – the operation failed, with an error reason.

Creating a Promise

const myPromise = new Promise((resolve, reject) => {
  let success = true;

  if (success) {
    resolve("Operation was successful!");
  } else {
    reject("Something went wrong.");
  }
});
  • resolve(value) → moves promise to fulfilled state.
  • reject(error) → moves promise to rejected state.

Handling Promises with .then() and .catch()

myPromise
  .then((result) => {
    console.log("Success:", result);
  })
  .catch((error) => {
    console.log("Error:", error);
  });
  • .then() runs when the promise is fulfilled.
  • .catch() runs when the promise is rejected.

Simulating asynchronous operation with setTimeout

javascript CopyEdit

const delayedPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Done after 2 seconds!");
  }, 2000);
});

delayedPromise
  .then((message) => {
    console.log(message); // "Done after 2 seconds!"
  })
  .catch((error) => {
    console.log(error);
  });
ConceptMeaning
PromiseRepresents a future value (or error)
resolveCompletes successfully (fulfilled)
rejectCompletes with failure (rejected)
.then()Handles success
.catch()Handles error
async/awaitCleaner way to write promise-based code

On this page