DEV Community

Mark Tony
Mark Tony

Posted on

JS - Promise

Promise Object

  • Promise is an object that holds an eventual result of an asynchronous operation.
  • Promises used to avoid nested callbacks (Callback Hell).
  • It makes readablilty and debuging easy.

Promise is like a promise statement made to a person that someone will fulfill what they have promised

const result = new Promise((resolve, reject) => {
  // async work happens here
});
Enter fullscreen mode Exit fullscreen mode

Promise has three states

  1. Pending (Initial Stage)
  2. Fulfilled
  3. Rejected

Pending (Initial Stage)
It is the initial stage indicating that the operation is being done.

Fulfilled:
It represents the success of the operation.

Rejected:
It indicates the error in the input or gives the failure output.

Example

if (age >= 18) {
  resolve("You are eligible to vote");   // Fulfilled path
} else {
  reject("You are not eligible to vote"); // Rejected path
}
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1> Promises</h1>
    <p id="para"> </p>
    <p id="error" style="color: red;"></p>
    <script>
 const result = new  Promise ((resolve, reject) => {
    const age = 28;
    setTimeout (() => {
     if (age >= 18) {
        resolve ("You are eligible to vote");
        } else {
            reject ("You are not eligible to vote");
        }
    },2000 )
 } )
  .then((data) => {
    console.log(data);
    document.getElementById("para").textContent = data;

 })
 .catch ( (error) => {
    console.error(error);
    document.getElementById("error").textContent = error;


 } );
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • The promise takes a function called executor. It runs immediately once the promise created.This executor receives two functions, resolve and reject.

resolve() and reject()

  1. resolve(value) — marks the Promise as fulfilled, and value gets passed to .then().
  2. reject(reason) — marks the Promise as rejected, and reason gets passed to .catch().

.then() and .catch()

Once a Promise settles, you get the outcome:

  1. .then(callback) — runs if the Promise resolved; callback receives the resolved value.
  2. .catch(callback) — runs if the Promise rejected; callback receives the rejection reason.

Promise chaining

.then() and .catch() are methods called on the Promise object, and each returns a new Promise, so you can chain more .then()s after it if needed.

Top comments (0)