Article Image

JavaScript

Interview-Preparation

Understanding Promises in JavaScript

What is a Promise in JavaScript?

A Promise in JavaScript is a specialized object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. A promise allows you to handle asynchronous code in a more manageable way by providing methods for dealing with success or failure outcomes, such as timeouts or network errors.

Creating a JavaScript Promise

To create a Promise, you use the new keyword, followed by the Promise constructor. The constructor takes a function known as the executor function, which has two parameters: resolve and reject. These methods determine the outcome of the Promise.

Example:

const myPromise = new Promise((resolve, reject) => {
  // Perform asynchronous operations here
});

Promise States

A Promise has three distinct states: pending, fulfilled, and rejected. These states represent the lifecycle of a Promise as it progresses through its execution.

  • Pending: The initial state when the Promise is still executing.
  • Fulfilled: The state when the Promise successfully resolves.
  • Rejected: The state when the Promise fails to resolve.

The resolve method is called when the Promise is fulfilled, and the reject method is called when it is rejected.

Example:

const myPromise = new Promise((resolve, reject) => {
  if (condition) {
    resolve("Promise fulfilled");
  } else {
    reject("Promise rejected");
  }
});

Promise States

const myPromise = new Promise((resolve, reject) => {
 if(condition here) {
   resolve("Promise was fulfilled");
 } else {
   reject("Promise was rejected");
 }
});

Handling a Promise

Promise States

Using the then Method

The then method is invoked when a Promise is fulfilled successfully. It takes a callback function that processes the result of the Promise.

Example:

myPromise.then(result => {
  // Handle the successful result
});

Using the catch Method

The catch method is used to handle rejected Promises. It is executed when a Promise is rejected, providing an opportunity to handle errors gracefully.

Example:

myPromise.catch(error => {
  // Handle the error
});

Async/Await

The async and await keywords offer a more readable and synchronous approach to handling Promises.

  • async: Marks a function as asynchronous and automatically returns a Promise.
  • await: Pauses the execution of an async function until a Promise is resolved.

Async Function

An async function always returns a Promise, regardless of what it returns.

Example:

async function myFunction() {
  return "Hello";
}

This is equivalent to:

async function myFunction() {
  return Promise.resolve("Hello");
}

Await Keyword

The await keyword causes JavaScript to wait for a Promise to resolve before continuing with the execution of the next line of code. It can only be used inside an async function.

Example:

async function fetchData() {
  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("Done!"), 1000);
  });

  let result = await promise;  // Wait for the promise to resolve
  alert(result);  // "Done!"
}

Implementing Promises

Here’s an example of using Promise.all to run multiple promises concurrently. This allows you to wait for multiple asynchronous tasks to finish before proceeding.

Example:

const pr1 = new Promise((resolve) => {
  setTimeout(() => resolve("Hello"), 4000);
});

const pr2 = new Promise((resolve) => {
  setTimeout(() => resolve("World"), 0);
});

const runPromises = async () => {
  try {
    const results = await Promise.all([pr1, pr2]);
    console.log(results);  // ["Hello", "World"]
  } catch (error) {
    console.error(error);
  }
};

runPromises();

Conclusion

JavaScript Promises are a powerful tool for handling asynchronous operations. By understanding how to create and manage Promises, you can write more efficient, readable, and maintainable code. The combination of async and await provides a convenient syntax for working with Promises, offering a more synchronous-like experience while maintaining asynchronous behavior.


References:

Thanks for reading!!!

Muneer Ahmed

Author

0