How do you use the Promise.finally() method in JavaScript?

The Promise.finally() method was introduced in ES2018 and it provides a way to execute a block of code regardless of whether the promise is fulfilled or rejected.

The basics of Promises:

Before we dive into the Promise.finally() method, let’s take a brief look at Promises in JavaScript.

A Promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. The Promise constructor takes a function as an argument, which has two parameters: resolve and reject. The resolve function is called when the operation is successful and the reject function is called when it fails.

For example:

const myPromise = new Promise((resolve, reject) => {
  // Perform an asynchronous operation
  if (operationSuccessful) {
    resolve(result);
  } else {
    reject(error);
  }
});

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

The then() method is used to handle the result of a successful Promise and the catch() method is used to handle errors. Promises can be chained together using the then() method, allowing us to perform a series of asynchronous operations in a sequence.

The Promise.finally() method:

The Promise.finally() method is a new addition to the Promise API in ES2018. It allows us to execute a block of code after a Promise has been settled, whether it was fulfilled or rejected. The finally() method takes a function as an argument, which is called regardless of whether the Promise was fulfilled or rejected.

myPromise
  .then((result) => {
    // Handle the result
  })
  .catch((error) => {
    // Handle the error
  })
  .finally(() => {
    // Execute this code block regardless of whether the Promise was fulfilled or rejected
  });

The finally() method can be useful for performing cleanup tasks or resetting the state of an application after an asynchronous operation has completed.

Example usage of Promise.finally():

Let’s take a look at a few examples of how to use the Promise.finally() method in practice.

Example 1: Basic usage:

In this example, we will create a Promise that resolves after a delay of 1 second. We will use the finally() method to log a message to the console after the Promise has settled.

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Success!");
  }, 1000);
});

myPromise
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.error(error);
  })
  .finally(() => {
    console.log("Promise settled");
  });

When we run this code, we should see the following output:

Success!
Promise settled

Example 2: Error handling:

In this example, we will create a Promise that rejects with an error message. We will use the finally() method to log a message to the console after the Promise has settled, regardless of whether it was rejected or not.

const myPromise = new Promise((resolve, reject) => {
  reject(new Error("Something went wrong"));
});

myPromise
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.error(error.message);
  })
  .finally(() => {
    console.log("Promise settled");
  });

Output:

Something went wrong
Promise settled

Example 3: Cleanup tasks:

In this example, we will create a Promise that resolves with some data. We will use the finally() method to clean up any resources that were used during the Promise operation, such as closing a file or releasing a network connection.

const myPromise = new Promise((resolve, reject) => {
  // Open a file or establish a network connection
  // ...

  resolve("Data");
});

myPromise
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.error(error);
  })
  .finally(() => {
    // Close the file or release the network connection
    // ...
  });

In this example, the finally() method is used to execute cleanup code that should always run, regardless of whether the Promise was fulfilled or rejected.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: