Promises, promises! In JavaScript, a Promise represents a value that may not be available yet, but will be resolved at some point in the future or rejected entirely.

Promises are one of the ways to handle asynchronous operations in JavaScript.

JavaScript Promises

What is a Promise? Link to heading

In JavaScript, a Promise is an object representing the eventual completion or failure of an asynchronous operation. It serves as a placeholder for the eventual results of the operation.

Here’s an example of how to create a Promise:

let p = new Promise((resolve, reject) => {
    let a = 1 + 1;
    if (a == 2) {
        resolve('Success!');
    } else {
        reject('Failed!');
    }
});

p.then(message => {
    console.log('This is in the then ' + message);
}).catch(err => {
    console.log('This is the catch ' + err);
});

In the above code, we are creating a new Promise that tests a simple arithmetic operation. If the operation is successful, we resolve the Promise with a success message, and if it fails, we reject the Promise with a failure message.

Promise States Link to heading

A Promise is in one of the following states:

  1. Pending: The Promise’s outcome hasn’t yet been determined, because the asynchronous operation that will produce its result hasn’t completed yet.
  2. Fulfilled: The asynchronous operation has completed, and the Promise has a resulting value.
  3. Rejected: The asynchronous operation failed, and the Promise will never be fulfilled. In the rejected state, a Promise has a reason that indicates why the operation failed.

Promise Methods Link to heading

Promises have several methods, but the most commonly used are .then(), .catch(), and .finally().

The .then() method is called when the Promise is resolved and the Promise’s result is known (the operation was successful).

The .catch() method is called when the Promise is rejected (the operation failed).

The .finally() method is called when the Promise is settled, whether fulfilled or rejected.

Conclusion Link to heading

Promises are a powerful tool to handle asynchronous operations in JavaScript. They allow us to write asynchronous code in a more synchronous fashion, making it easier to read and reason about.

Remember, a Promise is a JavaScript object representing the eventual completion or failure of an asynchronous operation. So next time when you see a Promise, just think of it as a promise that JavaScript makes to us that it will get back to us with the results of the asynchronous operation when it’s ready.