The .finally() Method
You'll learn how to run cleanup logic after a Promise settles, regardless of success or failure.
What is .finally()?
The .finally() method attaches a callback that runs after a Promise settles—whether it resolves or rejects. Think of it like washing your hands after cooking: whether the meal turned out great or burned, you still need to clean up.
Unlike .then() and .catch(), .finally() receives no arguments. It doesn't know if the Promise succeeded or failed, and it doesn't care. Its job is purely cleanup or finalization.
Why Use .finally()?
Imagine showing a loading spinner while fetching data:
showLoadingSpinner();
fetchData()
.then(data => {
displayData(data);
})
.catch(error => {
showError(error);
})
.finally(() => {
hideLoadingSpinner(); // Always hide spinner
});
Without .finally(), you'd need to call hideLoadingSpinner() in both .then() and .catch(). That's duplication and a maintenance headache.
Key Behaviors
- No arguments: The callback receives nothing—it can't access resolve values or rejection reasons
- Doesn't transform:
.finally()passes through the original settled value/reason - Always runs: Executes whether the chain succeeded or failed
Promise.resolve(42)
.finally(() => {
console.log('Cleanup done!');
})
.then(value => {
console.log(value); // Still logs 42
});
The cleanup happens, but the value continues down the chain unchanged.
Key Takeaway: Use .finally() for cleanup logic that must run regardless of Promise outcome—like closing connections, hiding UI elements, or releasing resources—without caring about success or failure details.