
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use Finally on Promise with Then and Catch in JavaScript
Javascript asynchronous programming uses a promise object which does not block the execution of the current flow but informs the compiler that there is something that is not completed yet, and whenever it completes it returns a signal to the system. There are mainly two possibilities. Either the promise object will complete successfully, or it will stop by returning an exception. To handle exceptions coming from promise objects the catch() methods are used. In try-catch methods also we can use another block named ?finally'. This will execute no matter what is done previously. For promises also we can use the finally() function to do the same. So in this article, our ultimate goal is to understand how to use finally on promise with the then() and catch() javascript methods.
The basic syntax is like below ?
Syntax
promise .then( // do something with the result result => { ...} ) .catch( // handle error error => { ... } ) .finally( // do something when it has been executed successfully // or raised an error. // this work can be memory cleaning or similar task () => { ... } )
Regardless of whether the promise is accepted or rejected, the finally() method is always carried out. In other words, the promise is settled when the finally() procedure is called. In ES2018, the finally() function debuted. The code that destructs the resource when the promise is fulfilled, regardless of its result, can be put in the finally() method. Without using the finally() method, we need to clear our resources inside then() and catch() methods.
Without Finally
promise .then( // do something with the result result => { ...} // do something to clear resources ) .catch( // handle error error => { ... } // do something to clear resources )
The then() and catch() blocks contain duplicate code. By adding a finally() block, this repetition may be easily avoided. The try...catch...finally statement ?finally' blocks and the finally() function are related constructs. For resource cleanup in synchronous programming, use the ?finally' block. The finally() method is used in asynchronous programs instead.
Let us see an example where we are creating a ?Connection' class to create a database connection (assume). There are two different methods, the run() method to execute a query and another method called terminate() to terminate the connection and clean up the resources. The connection class is defined as follows:
Connection Class
class Connection { run( query ) { if (query != 'Add' && query != 'Modify' && query != 'Remove') { throw new Error( `Invalid query: ${query}`); } console.log(`Running given query: ${query}`); return this; } terminate() { console.log( 'Terminating already connected connection' ) } }
Then we define a connect() method which will create a connection object and return a promise object to deal with the connection. When it completes its action a new connection object is returned, otherwise, an error is raised. Let us see the function definition for clear understanding.
Connect method
class Connection { run( query ) { if (query != 'Add' && query != 'Modify' && query != 'Remove') { throw new Error( `Invalid query: ${query}`); } console.log(`Running given query: ${query}`); return this; } terminate() { console.log( 'Terminating already connected connection' ) } }
Utilize the finally() block to handle the scenario in the end. In the example below: Because the success flag is set to true, the connect() function resolves to a fresh Connection object. The Insert query is executed via the first then() method, which also returns a Connection object. The connection is saved via the globalConnection. The Select query is run by the second then() function, which also throws an error. The finally() method ends the connection while the catch() method displays the error message.
Use of finally method
let globalConnection; connect() .then( (connection) => { globalConnection = connection; return globalConnection.run( 'Add' ); }) .then( (connection) => { globalConnection = connection; return globalConnection.run( 'Remove' ); }) .then((connection) => { globalConnection = connection; return connection.run( 'Union' ); }) .catch( console.log ) .finally( () => { if ( globalConnection ) { globalConnection.terminate(); } });
The complete code and corresponding output are given below?
Source Code
class Connection { run( query ) { if (query != 'Add' && query != 'Modify' && query != 'Remove') { throw new Error( `Invalid query: ${query}`); } console.log(`Running given query: ${query}`); return this; } terminate() { console.log( 'Terminating already connected connection' ) } } const success = true; function connect() { return new Promise( (resolve, reject) => { if ( success ) resolve( new Connection() ); else reject( 'Connection cannot be created' ); }); } let globalConnection; connect() .then( (connection) => { globalConnection = connection; return globalConnection.run( 'Add' ); }) .then( (connection) => { globalConnection = connection; return globalConnection.run( 'Remove' ); }) .then((connection) => { globalConnection = connection; return connection.run( 'Union' ); }) .catch( console.log ) .finally( () => { if ( globalConnection ) { globalConnection.terminate(); } });
Output
Running given query: Add Running given query: Remove Error: Invalid query: Union at Connection.run (/home/cg/root/18775/main.js:4:16) at /home/cg/root/18775/main.js:36:25 Terminating already connected connection
The promise is settled using the finally() method, which causes a function to run when it is either fulfilled or refused. Regardless of how the promise turns out, it's best to put the code that decommissions the resources in the finally() procedure.
Conclusion
When building and distributing a system to another platform or constructing a usable platform, exception handling is a crucial task. Try-catch blocks are used in exception handling. The catch block's purpose is to handle the exception using established logic. Another block we employ with them is one we call "finally," which runs whether an exception occurs or not. But synchronous systems only should use this process. The error may appear later in asynchronous programming as a result of a delayed response. To manage exceptions, we can utilize the then() method, which is akin to a try block. However, we utilize the finally() function, in this case, to get the same result as the "finally" block. Whenever the promise has been carried out successfully or there has been a mistake, this function is typically used to do cleanup actions.