JavaScript Promise finally() Method Tutorial

In this section, we will learn what the Promise finally() method is and how to use it in JavaScript.

Note: we’re assuming you’re already familiar with the Promise in general and the `then` and `catch` methods.

What is Promise finally() Method in JavaScript?

After a promise-object is settled (Either resolved or rejected) we might want to run a set of instructions afterwards. This is where the `finally` method can be used.

This method is useful for avoiding code duplication between onResolved and onRejection handlers. Importantly, the handler does not have any way of determining if the promise was resolved or rejected, so this method is designed to be used for things like cleanup, etc.

Promise finally() Method Syntax:

promise.finally(handler);

Promise finally() Method Parameters

This method takes one function as its input, but unlike other handlers in the `catch` and `then` methods, the function does not take any argument.

Promise finally() Method return value

This method also returns a promise. This promise, however, is the promise that the last handler before the `finally` method returned. For example, if the last handler before the `finally` method, returned a rejected Promise object, then the finally method will return that as well.

Example: using Promise finally() method in JavaScript

function exe(resolve, reject){
  setTimeout(()=>{
    reject("Failed");
  },2000);
}

const prom = new Promise(exe);

prom.then(value=>{
  console.log("The resolved handler");
  console.log(value);
},failed=>{
  console.log("The rejection of the 'then' method");
  console.log(failed);
}).finally(()=>{
  console.log("The finally handler");
});

Output:

The rejection of the 'then' method

Failed

The finally handler
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies