Mastering Promises in JavaScript: A Comprehensive Guide


In JavaScript, a Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It provides a cleaner and more efficient way to handle asynchronous code compared to traditional callback-based approaches.

A Promise has three states:

  • Pending: The initial state when a Promise is created. The asynchronous operation is still in progress, and the Promise is neither fulfilled nor rejected.
  • Fulfilled: The state when the asynchronous operation is completed successfully. The Promise has a resulting value associated with it, which can be accessed using the .then() method.
  • Rejected: The state when the asynchronous operation encounters an error or is rejected explicitly. The Promise has a reason or error associated with it, which can be accessed using the .catch() method.

Promises can be used to handle various asynchronous operations such as fetching data from APIs, making HTTP requests, reading/writing files, and more. Promises can be chained together using the .then() method, allowing for sequential execution of asynchronous operations. Additionally, Promises can be combined using methods like Promise.all() and Promise.race() to handle multiple asynchronous operations concurrently.

ES6 introduced the async/await syntax, which is built on top of Promises and provides a more concise way to write asynchronous code. async functions return Promises, and await is used to pause the execution of an asynchronous function until the Promise is fulfilled or rejected.

Key features of Promises in JavaScript:

  • Asynchronous handling: Promises provide a way to handle asynchronous operations in a more organized and readable manner.
  • Error handling: Promises have built-in error handling through the .catch() method, allowing for centralized error handling.
  • Chaining: Promises can be chained together using the .then() method, allowing for sequential execution of asynchronous operations.
  • Concurrency: Promises can be combined using methods like Promise.all() and Promise.race() to handle multiple asynchronous operations concurrently.
  • Compatibility: Promises are widely supported in modern JavaScript environments and can be used in both browser-based and server-side JavaScript applications.

Overall, Promises in JavaScript provide a powerful tool for managing asynchronous code, making it more manageable, readable, and error-resistant.

then()

then() is a method available on Promise objects. It is used to attach callbacks or handlers that will be executed when a Promise is fulfilled, i.e., when the asynchronous operation associated with the Promise completes successfully.

The syntax for using then() is as follows:

promise.then(onFulfilled, onRejected);

where promise is the Promise object, onFulfilled is a callback function that will be executed when the Promise is fulfilled, and onRejected is an optional callback function that will be executed when the Promise is rejected

The onFulfilled callback function will receive the resolved value of the Promise as its first argument. If the Promise does not have a resolved value, onFulfilled will receive undefined. The onRejected callback function, if provided, will receive the reason or error associated with the rejected Promise as its first argument.

resolve and reject

The resolve and reject functions are provided as arguments to the Promise constructor, and they are used to fulfill or reject the Promise, respectively, when the asynchronous operation completes.

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" type="image/ico" href="logo.png" />
    <title>Document</title>
    <style>
      @import url("https://fonts.googleapis.com/css2?family=Lobster&family=Poppins:wght@100;200;300;400;500;600;700;800&display=swap");
      * {
        font-family: "Poppins", sans-serif;
      }
    </style>
  </head>
  <body>
    <h3>Promise in JavaScript</h3>
    <button>Click Me</button>
    <script src="117_promise.js"></script>
  </body>
</html>

script.js

/*
const promise = new Promise((resolve, reject) => {
  const sum = 22 + 1;
  if (sum == 2) {
    resolve("Success");
  } else {
    reject("Error");
  }
});

promise
  .then((msg) => {
    console.log(msg);
  })
  .catch((error) => {
    console.error(error);
  });

  */

/*
setTimeout(() => {
  console.log("Hi");
}, 250);

function setTimeoutPromise(duration) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, duration);
  });
}
setTimeoutPromise(250).then(() => {
  console.log("Joes");
});
*/

/*
setTimeout(() => {
  console.log("Normal : 1");

  setTimeout(() => {
    console.log("Normal : 2");

    setTimeout(() => {
      console.log("Normal : 3");
    }, 250);
  }, 250);
}, 250);

function setTimeoutPromise(duration) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, duration);
  });
}

setTimeoutPromise(250).then(() => {
  console.log("Normal SetTime : 1");

  setTimeoutPromise(250).then(() => {
    console.log("Normal SetTime : 2");

    setTimeoutPromise(250).then(() => {
      console.log("Normal SetTime : 3");
    });
  });
});


setTimeoutPromise(250)
  .then(() => {
    console.log("Cool Promise : 1");
    return setTimeoutPromise(250);
  })
  .then(() => {
    console.log("Cool Promise : 2");
    return setTimeoutPromise(250);
  })
  .then(() => {
    console.log("Cool Promise : 3");
  });
*/

/*
const button = document.querySelector("button");

function addEventPromise(element, method) {
  return new Promise((resolve, reject) => {
    element.addEventListener(method, resolve);
  });
}

addEventPromise(button, "click").then((e) => {
  console.log("Clicked");
  console.log(e);
});

*/

/*
console.log(Promise.resolve("Good"));

Promise.all([Promise.resolve("Good"), Promise.resolve("Good"), Promise.resolve("Good")])
  .then((msg) => {
    console.log(msg);
  })
  .catch((error) => {
    console.error(error);
  });

Promise.all([Promise.resolve("Good"), Promise.reject("Error"), Promise.resolve("Good")])
  .then((msg) => {
    console.log(msg);
  })
  .catch((error) => {
    console.error(error);
  });

Promise.any([Promise.reject("1"), Promise.reject("Error"), Promise.resolve("3")])
  .then((msg) => {
    console.log(msg);
  })
  .catch((error) => {
    console.error(error);
  });

Promise.race([Promise.reject("Good-1"), Promise.resolve("Good-2"), Promise.resolve("Good-3")])
  .then((msg) => {
    console.log(msg);
  })
  .catch((error) => {
    console.error(error);
  });


Promise.allSettled([Promise.reject("Good-1"), Promise.resolve("Good-2"), Promise.resolve("Good-3")])
  .then((msg) => {
    console.log(msg);
  })
  .catch((error) => {
    console.error(error);
  });
*/

/*
const promise = Promise.reject("Error");

promise
  .then((msg) => {
    console.log(msg);
  })
  .catch((err) => {
    console.error(err);
  })
  .finally(() => {
    console.log("All Completed..");
  });
*/

/*
const getPost = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const posts = ["Post-1", "Post-2", "Post-3"];
      resolve(posts);
    }, 1000);
  });
};

const getComments = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const comments = ["Comment 1", "Comment 2", "Comment 3"];
      resolve(comments);
    }, 2000);
  });
};

Promise.all([getPost(), getComments()])
  .then((results) => {
    //console.log(results);
    const [posts, comments] = results;
    console.log(`Posts: ${posts}`);
    console.log(`Comments: ${comments}`);
  })
  .catch((err) => {
    console.error(err);
  });

*/

/*
fetch("https://jsonplaceholder.typicode.com/users")
  .then((response) => response.json())
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.error(err);
  });
*/

List of Programs


JS Practical Questions & Answers


JS Practical Project