Skip to main content
Practice

Promise

A Promise is an object representing the result of an asynchronous operation in JavaScript.

What does asynchronous mean here?


Synchronous & Asynchronous Communication

Network communication can be broadly classified into Synchronous and Asynchronous communication.

In synchronous communication, tasks are processed one after another, with subsequent tasks waiting for the previous ones to complete. In contrast, asynchronous communication allows multiple tasks to be processed simultaneously, handling results as each specific task completes.


Promise

A Promise is an object representing the result of an asynchronous operation in JavaScript.

The English word "Promise" implies a guarantee to provide a result at some point in the future. This concept allows for waiting until an asynchronous operation is complete and then performing additional tasks based on whether the operation was successful or failed.

Promises are commonly used to handle asynchronous tasks such as server communication and event handling.


Example usage of Promise
const myPromise = new Promise((resolve, reject) => {
const isDone = true;

if (isDone) {
resolve('Task completed');
} else {
reject('Task failed');
}
});

myPromise
.then((result) => {
console.log(result); // Task completed
})
.catch((error) => {
console.log(error); // Task failed
});

The above example creates a Promise object and assigns it to the constant myPromise. The myPromise.then method registers a callback function that will be called when the asynchronous operation completes successfully.

Conversely, the myPromise.catch method registers a callback function to handle when the asynchronous operation fails.

The Promise calls resolve() upon successful completion of the task and reject() if the task fails.


Features of Promise

  1. States: A Promise has three states:
  • Pending: The asynchronous operation has not yet completed.

  • Fulfilled: The asynchronous operation has completed successfully and the Promise returns a resultant value.

  • Rejected: The asynchronous operation has failed and the Promise returns the reason for the failure.


  1. then and catch:
  • .then(): Called when the Promise completes successfully.

  • .catch(): Called when the Promise fails.

  • .finally(): Called regardless of whether the Promise was successful or failed.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.