Course contentsShow
← JavaScript
Lesson 1357 of 2,72330. Async/AwaitFree lesson

The Finally Block in Async Functions

Use finally to execute cleanup code regardless of success or failure in async operations.

The Finally Block in Async Functions

You'll learn how to use finally with try/catch blocks in async functions to guarantee cleanup code runs, whether your async operations succeed or fail.

What Finally Does in Async Functions

Just as .finally() works with promise chains, the finally block in a try/catch statement ensures certain code executes no matter what happens in your async function. It runs after the try block succeeds or after the catch block handles an error.

This is perfect for cleanup tasks: closing connections, hiding loading spinners, releasing resources, or logging operations—things you need to do regardless of success or failure.

The Pattern

async function fetchUserData(userId) {
  console.log('Loading...');
  
  try {
    const response = await fetch(`/api/users/${userId}`);
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Failed to fetch user:', error);
    throw error;
  } finally {
    console.log('Done loading'); // Always runs
  }
}

The finally block executes whether the fetch succeeds, fails, or even if you return early from the try block. It's your guaranteed "last chance" to run code before the function completes.

Think of It Like This

Imagine borrowing a library book (try), potentially losing it (catch), but always needing to sign the checkout sheet (finally) before leaving—no matter what happened with the book.

Key Takeaway: Use finally in async functions to execute cleanup code that must run regardless of whether your await operations succeed or fail—it's your safety net for resource management and state cleanup.