JavaScript Promise

About JavaScript Promise

In JavaScript, a Promise is an object representing the eventual completion (success) or failure of an asynchronous operation and its resulting value.

Promises help avoid "callback hell" and make asynchronous code more readable and manageable.

Promises should be used when dealing with asynchronous operations, such as API calls, file reading, or any operation that takes time to complete.

A Promise can be used to chain multiple asynchronous operations together, allowing you to handle the results of each operation in a clean and organized way.

States of a Promise

A Promise can be in one of three states:

  • Pending : This is the initial state, meaning the asynchronous operation hasn't completed yet.
  • Fulfilled (Resolved) : This state indicates that the asynchronous operation completed successfully, and the Promise has a resulting value.
  • Rejected : This state indicates that the asynchronous operation failed, and the Promise has a reason for the failure (usually an error).

Creating a Promise

A Promise can be created by using the Promise constructor (new Promise()), which takes a function called the "executor function" as an argument. This executor function receives two arguments: resolve and reject.

The resolve function is called when the asynchronous operation is successful, and it takes the result as an argument.

The reject function is called when the operation fails, and it takes an error message as an argument.

The following example demonstrates how to create a Promise that simulates an asynchronous operation (e.g., fetching data) and resolves or rejects based on a condition.


Explanation of the Code
  • const myPromise = new Promise((resolve, reject) => ..): This line creates a new Promise object and assigns it to the variable myPromise. The executor function takes two arguments: resolve and reject.
  • setTimeout(() => {const success = true;...): This simulates an asynchronous operation using setTimeout function. After 3 seconds, it checks the value of success.
  • resolve("Data was fetched successfully!");: If the operation is successful, it calls the resolve function with the success message (Data was fetched successfully!).
  • reject("Failed to fetch data.");: If the operation fails, it calls the reject function with the error message (Failed to fetch data.).

Consuming a Promise

A Promise can be consumed using the .then(), .catch(), and .finally() methods. These methods allow you to handle the result of the Promise once it is fulfilled or rejected.

  • .then: This method is called when the Promise is fulfilled. It takes a callback function as an argument, which receives the resolved value as its parameter.
  • .catch: This method is called when the Promise is rejected. It takes a callback function as an argument, which receives the error message as its parameter.
  • .finally: This method is called when the Promise is settled, regardless of whether it was fulfilled or rejected. It takes a callback function as an argument, which does not receive any parameter.

The following example demonstrates how to consume the myPromise created in the previous section using .then(), .catch(), and .finally() methods.

Explanation of the Code
  • myPromise.then((resolve) => { console.log(resolve);}): This line calls the .then() method on the myPromise object. If the Promise is fulfilled, it logs the resolved value to the console.
  • .catch((error) => { console.error(error);}): This line calls the .catch() method on the myPromise object. If the Promise is rejected, it logs the error message to the console.
  • .finally(() => { console.log("Request completed.");}) : This line calls the .finally() method on the myPromise object. This will run always, regardless of whether the Promise was fulfilled or rejected.

Chaining Promises

JavaScript Chaining Promises refers to the process of linking multiple .then() calls together so that asynchronous operations are performed in a sequence, where the output of one step is passed to the next.

Promise chaining helps avoid deeply nested callbacks (i.e., "callback hell") and organize asynchronous logic into a readable sequence.

The following example demonstrates how to chain multiple Promises together, where each Promise depends on the result of the previous one.


In this example, we have three asynchronous tasks: firstTask, secondTask, and thirdTask. Each task returns a Promise that resolves after a delay of 2 seconds. The result of each task is passed to the next task in the chain.

The firstTask is called first, and once it resolves, its result is passed to the secondTask. After the secondTask resolves, its result is passed to the thirdTask. Finally, the result of the third task is logged to the console.

If any of the tasks fail, the .catch() method will handle the error and log it to the console.

If one of the tasks fails, there will be no further execution of the subsequent tasks, and the error will be caught in the .catch() block.

Run Multiple Promises in Parallel

Promise.all() is a powerful method provided by JavaScript to run multiple promises in parallel and wait until all of them are fulfilled (or one fails).

It takes an array of Promises as an argument and returns a new Promise that resolves when all the Promises in the array have resolved, or rejects immediately if any promise rejects.

The following example demonstrates how to use Promise.all() to run multiple Promises in parallel and handle their results.


Explanation of the Code
  • const p1 = new Promise(resolve => setTimeout(() => resolve('First Promise'), 1000));: This line creates a new Promise p1 that resolves after 1 second with the value 'First Promise'.
  • const p2 = new Promise(resolve => setTimeout(() => resolve('Second Promise'), 2000));: This line creates a new Promise p2 that resolves after 2 seconds with the value 'Second Promise'.
  • const p3 = new Promise(resolve => setTimeout(() => resolve('Third Promise'), 1500));: This line creates a new Promise p3 that resolves after 1.5 seconds with the value 'Third Promise'.
  • Promise.all([p1, p2, p3]): This line uses Promise.all() to run all three promises in parallel. It takes an array of promises as an argument.
  • .then(results => { console.log(results); }): This line is called when all promises are fulfilled. It logs the results of all promises as an array to the console.

JavaScript Compiler For Live Practice

Practice the above JavaScript code in the following JavaScript Editor. Create more Promises in the following editor and click Execute button to check the output. The output will be displayed in JavaScript Code Output section.

JavaScript logo JavaScript Editor
JavaScript Code Output