What is the finally() method in JavaScript?

Topics Covered

What is the finally() Method in JavaScript?

The finally() method is used to return a Promise, when a promise is settled, Like then() and catch(), that is either fulfilled or rejected. When handling errors with a try and catch block, It is a block of code that will be executed regardless of the situation. Javascript finally was introduced in ES2018 and using the finally() method, duplication of code can be avoided in the then() and catch() methods of the Promise.

A JavaScript object called a Promise is created when an asynchronous function runs successfully and generates a value. It generates an error if it cannot execute successfully due to a timeout. Javascript finally block is written after try and catch block, and finally will be executed definitely when either any one of the blocks i.e. try or catch is executed.

Syntax

The syntax of the javascript finally method is shown below:

Description

Since javascript finally always executes whether the promise is accepted or rejected, it can be used to perform cleanup tasks after the promise has been settled. Additionally, it stops the then() and catch() methods of the Promise from having duplicate code.

Similar to the finally block in the try...catch...finally statement is the finally() method. The finally block is used to clean up resources in synchronous code. Instead, use the finally() method when writing asynchronous code.

The javascript finally method is very similar to calling .then(onFinally, onFinally), but, here are some couple of differences listed below:

  • Instead of having to declare a function twice or create a variable for it, you can pass it once when creating it inline.
  • A Javascript finally callback will not accept any argument. And this use case should only be applied when there is no need to provide the rejection reason or fulfilment value, i.e., when you don't care about either.
  • Typically, a finally call will chain through a suitable alternative for the original promise. So for example:
    • Unlike Promise.resolve(4).then(() => 11, () => {}) (that will return a resolved promise with the result 11), Promise.resolve(4).finally(() => 11) will return a new resolved promise with the result 4.
    • Similarly, Promise.reject(2).then(() => {}, () => 55) (that will return a resolved promise with the result 55), Promise.reject(2).finally(() => 55) will return a rejected promise with the reason 2.
    • But, both the Promise.reject(2).finally(() => {throw 66}) and Promise.reject(2).finally(() => Promise.reject(66)) will reject the returned promise with the reason 66.

How does Finally Works in JavaScript?

A try-catch statement is always used with the finally block. Only the try statement or the try with catch statement and finally block are allowed. The code that will be run and could result in an error is specified in the try block. This error may be the result of a programmer error or a runtime problem. The catch block will be executed if the code in the try block fails.

In the event of failure, the catch block allows for the necessary action to be taken. The finally block will be executed in any circumstance when either the try or catch blocks have been executed. While using a try statement, at least one of the catch and finally statements must be used. It is not required to use both at once.

Examples

The examples of javascript finally method are given below:

Using Finally With No Catch Block

Output

Using finally with no catch block1

Using finally with no catch block2

Explanation

Since we are using finally with no catch block, the finally block is called even if the code in the try block fails because there is no catch block and no way to handle errors in this situation. As we know finally block will always executes, even if we have return statement in try block or any exception.

A Connection Class

A Connection class is defined by the following:

Execute() and Close() are two methods available in the Connection class.

  • The execute() method only executes the insert, update, or delete query. If you enter another query that isn't on the list, an error will be raised.
  • The close() method ends the connection and mainly cleans up the resource.

If the flag is set to true, the connect() function will return a promise that will resolve to a new Connection as shown in the below example:

The finally() method is used to close the connection in the example below:

Explanation

Since the flag is set to true, the connect() function resolves to a new Connection object. The Insert query is executed by the first then() method, which also returns a Connection object. The connection is saved using the global variable. The Select query is run by the second then() method, which also throws an error. The finally() method closes the connection while the catch() method displays the error message.

Try Block Successful Execution

Output

Try block successful execution1

Try block successful execution2

Explanation

Here, try, catch, and finally are the three functions that will be used to correspond to the three blocks. We will be calling the appropriate functions from the respective blocks in try-catch statements. This is an example of error-prone code because the try block contains a nonexistent function that the programmer might call.

Try Block Failure

Output

Try block failure1

Try block failure2

Explanation

Due to an error, the catch block is executed in this case, and the appropriate catch function is passed. Here, take note of how we used a catch block to capture the error and passed it to the function. Finally block is also invoked in this instance.

Conclusion

  • The finally() method is used to return a Promise, when a promise is settled, Like then() and catch(), that is either fulfilled or rejected.
  • Javascript finally was introduced in ES2018 and using the finally() method, duplication of code can be avoided in the then() and catch() methods of the Promise.
  • An object called a Promise is created when an asynchronous function runs successfully and generates a value. It generates an error if it cannot execute fully due to a timeout.
  • Javascript finally takes onFinally function as a parameter and returns an equivalent Promise whose finally handler is set to the specified function.
  • The finally block is used to clean up resources in synchronous code. Instead, use the finally() method when writing asynchronous code. The javascript finally method is very similar to calling .then(onFinally, onFinally).
  • We can use finally with no catch block as we know finally block always executes, even if we have exception or return statement in try block.
  • The finally block will be executed in any circumstance when either the try or catch blocks have been executed. While using a try statement, at least one of the catch and finally statements must be used.