Course contentsShow
← JavaScript
Lesson 1327 of 2,72329. PromisesFree lesson

Finally for Cleanup Actions

Using finally to run code whether the promise succeeds or fails, without affecting the result.

Finally for Cleanup Actions

You'll learn how to use .finally() to run cleanup code that executes regardless of promise success or failure, without interfering with the promise's result.

What Is Finally For?

When working with promises, you often have cleanup tasks that need to happen no matter what: closing database connections, hiding loading spinners, clearing timers, or releasing resources. The .finally() method is designed specifically for this—it runs whether the promise resolves or rejects, and crucially, it doesn't modify the promise's result.

Think of .finally() like the closing paragraph of an essay: no matter what argument you made (success or failure), you always include it, and it doesn't change your main points.

How Finally Works

Unlike .then() and .catch(), which can transform values or change the success/failure path, .finally() is transparent. The value or error passes through it unchanged:

fetchUserData()
  .then(data => {
    displayUser(data);
    return data;
  })
  .catch(error => {
    showError(error.message);
    throw error;
  })
  .finally(() => {
    hideLoadingSpinner(); // Runs either way
  });

The loading spinner disappears whether the fetch succeeds or fails, but the data or error continues downstream untouched.

Common Cleanup Scenarios

// Example: File operation cleanup
openFile('data.txt')
  .then(file => processFile(file))
  .catch(error => logError(error))
  .finally(() => {
    closeFile(); // Always close, success or failure
  });

Notice that .finally() receives no arguments—it doesn't know or care about the promise's result. It's purely for side effects.

Key Takeaway: Use .finally() for cleanup actions that must run regardless of success or failure; it executes last but passes the original result through unchanged, making it perfect for resource cleanup, UI state resets, and closing connections.