DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

What is a Promise in JavaScript?

A Promise is an object in JavaScript that represents the eventual success or failure of an asynchronous operation.

Real-life example:

You order food online.

  • Pending — your food is being prepared.
  • Fulfilled — your food has arrived successfully.
  • Rejected — your order has failed.

These are the three states of a JavaScript Promise.

  1. Pending:
    The operation is still in progress.

  2. Fulfilled:
    The operation completed successfully.

  3. Rejected:
    The operation failed.

  4. Promise syntax:

const myPromise = new Promise((resolve, reject) => {
// Perform a task

resolve("Success!");
// reject("Something went wrong!");
Enter fullscreen mode Exit fullscreen mode

});

Here:

  • new Promise() — creates a Promise.
  • resolve() — indicates successful completion.
  • reject() — indicates failure.

Usually, you call either resolve() or reject() when the operation finishes.

  1. Simple Promise example:

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

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

});

myPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});

Output:
Task completed successfully!

Change success = true to success = false.

Output:
Task failed!

Top comments (0)