How to use the finally() method in promise chains
The finally() method is an important feature of promise chains in JavaScript that allows us to define a callback function to be executed, regardless of whether the promise is fulfilled or rejected. It provides a way to perform cleanup operations or execute tasks that should be done regardless of the promise outcome.
Function syntax
The finally() method is called on a promise object and takes a callback function as an argument. The syntax is as follows:
promise.finally(callback);
- The
finally()method is called on thepromiseobject. - A
callbackfunction is executed when thepromiseis settled, whether fulfilled or rejected.
Possible usage
The finally() method can be used in the following various scenarios.
-
Cleanup operations: These include performing cleanup tasks such as releasing resources, closing connections, or resetting states, regardless of the promise outcome.
-
Common actions: These include executing common actions that need to occur in both success and error scenarios, such as logging, updating UI elements, or triggering additional operations.
-
Promise chain finalization: Here, we use
finally()to conclude a promise chain and specify the last steps to be executed. -
Resource cleanup: Here, we use
finally()to release resources like file handles, network connections, or database connections. This ensures that resources are properly released, even if exceptions occur during the promise chain.
Code example
Here’s an example that demonstrates the usage of the finally() method in a promise chain:
function fetchData() {return new Promise((resolve, reject) => {// Simulating an asynchronous operationsetTimeout(() => {const randomNum = Math.random();if (randomNum < 0.5) {resolve("Data fetched successfully!");} else {reject("Error occurred while fetching data.");}}, 2000);});}fetchData().then((data) => {console.log("Success:", data);// Additional success handling}).catch((error) => {console.log("Error:", error);// Additional error handling}).finally(() => {console.log("Cleanup: Closing database connection.");// Perform cleanup operations or final steps});
Code explanation
-
Lines 1–13: The
fetchData()function returns a promise that simulates an asynchronous operation by usingsetTimeout()to introduce a delay of2000milliseconds (2 seconds). -
Lines 4–10: Inside the
setTimeout()callback, a random number is generated. If the number is less than0.5, the promise is fulfilled usingresolve(), and the success message is passed as the resolved value. Otherwise, the promise is rejected usingreject(), and the error message is passed as the rejected reason. -
Lines 15–19: The promise chain begins by calling
fetchData(). The subsequent.then()method is used to handle the fulfillment of the promise. In this example, it logs the success message received from the resolved promise. We can include additional success handling code inside thecallbackif needed. -
Lines 20–23: If an error occurs during the promise execution, the
.catch()method is called. It handles the rejected promise and logs the error message. We can include additional error handling code inside thecallbackif required. -
Lines 24–27: The
.finally()method is appended to the promise chain. It specifies acallbackfunction that will be executed, regardless of whether the promise is fulfilled or rejected. In this example, it logs the cleanup message indicating the closing of a database connection. We can include any necessary cleanup operations or final steps inside thefinally()callback.
By using the finally() method in a promise chain, we can ensure that cleanup tasks or common actions are performed reliably, improving code maintainability and readability.
Free Resources