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.
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);
finally()
method is called on the promise
object.callback
function is executed when the promise
is settled, whether fulfilled or rejected.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.
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});
Lines 1–13: The fetchData()
function returns a promise that simulates an asynchronous operation by using setTimeout()
to introduce a delay of 2000
milliseconds (2 seconds).
Lines 4–10: Inside the setTimeout()
callback, a random number is generated. If the number is less than 0.5
, the promise is fulfilled using resolve()
, and the success message is passed as the resolved value. Otherwise, the promise is rejected using reject()
, 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 the callback
if 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 the callback
if required.
Lines 24–27: The .finally()
method is appended to the promise chain. It specifies a callback
function 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 the finally()
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