2 Use Cases of the 'finally' Keyword in JavaScript
The finally
keyword is used in two places: synchronous try-catch-finally
blocks and asynchronous Promise chains.
Let's look at each of them one by one.
Synchronous try-catch-finally
Block
The finally
keyword is used in conjunction with a try
and catch
block to define a block of code that will be executed regardless of whether an exception is thrown or not.
The finally
block is often used to contain cleanup code or to ensure that certain tasks are performed regardless of whether an error occurs.
Here's a basic structure of how try
, catch
, and finally
work together:
try { // Code that may throw an exception // ... } catch (error) { // Code to handle the exception // ... } finally { // Code that will always be executed, regardless of whether an exception was thrown or caught // This is often used for cleanup operations // ... }
Asynchronous Promise Chain
ES2018 introduced the finally
method for promise objects, which serves a similar purpose as the finally
clause in a try-catch-finally
statement.
finally
keyword is used to specify a callback function that will be executed after the Promise is settled, whether it's resolved or rejected.
If you need to perform cleanup tasks, such as closing open files or network connections, regardless of the promise's outcome, a finally
callback is the perfect place to do so.
This callback does not receive any arguments, so you cannot determine whether the promise was fulfilled or rejected.
Here's an example of how finally
can be used in a Promise chain:
somePromiseReturningFunction() .then((result) => { // Code to handle the resolved value console.log(result); }) .catch((error) => { // Code to handle the rejected value console.error(error); }) .finally(() => { // Code that will be executed regardless of whether the Promise is resolved or rejected console.log("Finally block executed"); });
I have created a set of resources for learning asynchronous JavaScript. These guides—Callbacks, Promises, and Async/Await —cover everything I’ve learned from years of real-world JavaScript experience.
If you found this article helpful, you’ll get so much out of these guides. Each one is optimized for those “lightbulb moments,” building a strong mental model for how asynchronous JavaScript works and how you can use it to create fast, dynamic applications.