InterviewHubPRO
Section Overview
Q55

Question 55 of 521

Part 2: Promises, Callbacks, Async & Strict Mode (54 - 103)

11%
JavaScript Internals (521 Qs)•Part 2: Promises, Callbacks, Async & Strict Mode (54 - 103)

What is a promise

A Promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It acts as a placeholder for a value that may not be available yet but will be resolved in the future.

A Promise can be in one of three states:

  • pending: Initial state, neither fulfilled nor rejected.
  • fulfilled: The operation completed successfully.
  • rejected: The operation failed (e.g., due to a network error).

Promise Syntax

javascript
const promise = new Promise(function (resolve, reject) {
  // Perform async operation
});

Example: Creating and Using a Promise

javascript
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("I'm a Promise!");
  }, 5000);
});

promise
  .then((value) => console.log(value)) // Logs after 5 seconds: "I'm a Promise!"
  .catch((error) => console.error(error))  // Handles any rejection
  .finally(() => console.log("Done"));     // Runs regardless of success or failure

In the above example:

  • A Promise is created to handle an asynchronous operation with resolve and reject callbacks.
  • The setTimeout resolves the promise with a value after 5 seconds.
  • .then(), .catch(), and .finally() are used to handle success, errors, and cleanup respectively.

The action flow of a promise will be as below,

Screenshot