If you're like most people, you've probably heard of JavaScript Promises but you may not know exactly what they are or how they work. Promises are a way to make sure that certain code happens only after other code has completed. They're often used when dealing with asynchronous tasks, such as making an HTTP request.

Essentially, a promise is an object that represents the result of an asynchronous operation. A promise can be in one of three states:

  • pending - The asynchronous operation has not yet completed.
  • fulfilled - The asynchronous operation has completed successfully.
  • rejected - The asynchronous operation has failed.

Once a promise is fulfilled or rejected, it is said to be settled. A promise that is pending can not be settled.

How to write a promise in JavaScript

You can create a promise using the Promise constructor as follows:

const promise = new Promise((resolve, reject) => {
  // do something asynchronous which eventually calls either:
  //
  //   resolve(someValue); // fulfilled
  // or
  //   reject("failure reason"); // rejected
});

The code inside the Promise constructor is executed immediately. It is passed two arguments: resolve and reject. These are functions that you call when the asynchronous task is complete. If the task is successful, you call resolve. If the task fails, you call reject.

How to call a promise in JavaScript

Once you have created a promise, you can use it by calling one of the following methods:

promise.then((value) => {
  // success
}, (reason) => {
  // failure
});

promise.catch((reason) => {
  // failure
});

The then method takes two arguments: a success callback and a failure callback. The success callback is called if the promise is fulfilled. The failure callback is called if the promise is rejected.

The catch method is shorthand for promise.then(undefined, (reason) => { // failure }).

Important things you should know about promises

It is important to note that a promise can only be settled once. That is, if a promise is fulfilled, you can not fulfill it again. Similarly, if a promise is rejected, you can not rejected it again.

Once a promise is settled, the success or failure callback is called with a single argument. If the promise is fulfilled, the argument is the value that was passed to the resolve function. If the promise is rejected, the argument is the reason that was passed to the reject function.

It is important to note that a promise is not actually executed until you call one of the methods, such as then or catch.

You can also create a promise that is already fulfilled or rejected by using the Promise.resolve and Promise.reject methods as follows:

const promise = Promise.resolve("success");

// equivalent to:
const promise = new Promise((resolve, reject) => {
  resolve("success");
});

const promise = Promise.reject("failure");

// equivalent to:
const promise = new Promise((resolve, reject) => {
  reject("failure");
});

Benefit of using promises

One of the benefits of using promises is that you can chain them together.

That is, you can create a promise that is fulfilled by the result of another promise. For example, suppose you have a function that makes an HTTP request and returns a promise.

You can use the then method to chain together a series of HTTP requests as follows:

makeHttpRequest("/foo")
  .then((value) => {
    console.log(value);
    return makeHttpRequest("/bar");
  })
  .then((value) => {
    console.log(value);
  });

In the above example, the first HTTP request is made and the promise is returned.

The promise returned by makeHttpRequest("/foo") is passed to the then method.

The success callback is called with the value returned by the makeHttpRequest("/foo") function.

The value is then passed to the makeHttpRequest("/bar") function and the promise returned by that function is passed to the then method. The success callback is called with the value returned by the makeHttpRequest("/bar") function.

What happens if a promise chain gets rejected?

If any of the promises in the chain are rejected, the failure callback is called with the reason. For example:

makeHttpRequest("/foo")
  .then((value) => {
    console.log(value);
    return makeHttpRequest("/bar");
  })
  .then((value) => {
    console.log(value);
  })
  .catch((reason) => {
    console.log(reason);
  });

In the above example, the catch method is used to handle any failures. If the makeHttpRequest("/foo") promise is rejected, the failure callback is called with the reason. If the makeHttpRequest("/bar") promise is rejected, the failure callback is also called with the reason.

Promises are a powerful way to manage asynchronous code. They allow you to chain together a series of asynchronous operations and handle failures gracefully.

Share this post