Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 27 - The finally Block in Async/Await

In JavaScript, the finally block is used with try...catch to execute code regardless of whether an error occurs. It’s useful for cleanup tasks like closing connections or hiding loaders.


Explanation

  • finally runs after try and catch, whether an error occurs or not.
  • Common use cases:
    • Closing database connections.
    • Stopping a loading animation.
    • Resetting application states.

Example 1: Using finally to Clean Up

async function fetchData() {
    try {
        console.log("Fetching data...");
        let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
        let data = await response.json();
        console.log("Data received:", data);
    } catch (error) {
        console.error("Error:", error.message);
    } finally {
        console.log("Fetch attempt finished.");
    }
}

fetchData();
  • The finally block runs no matter what—after success or failure.

Example 2: Using finally to Stop a Loader

async function fetchUserData() {
    console.log("Loading...");

    try {
        let response = await fetch("https://jsonplaceholder.typicode.com/users/1");
        let user = await response.json();
        console.log("User:", user);
    } catch (error) {
        console.error("Failed to fetch user:", error.message);
    } finally {
        console.log("Hiding loader...");
    }
}

fetchUserData();
  • The loader is hidden regardless of success or failure.

Try Your Hand

Steps:

  1. Create a File:

    • Name it lesson27-finally.html.
  2. Write the Code:

    • Copy the following code:

      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Lesson 27 - Finally Block</title>
      </head>
      <body>
      <script>
         async function fetchData() {
             try {
                 console.log("Fetching data...");
                 let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
                 let data = await response.json();
                 console.log("Data received:", data);
             } catch (error) {
                 console.error("Error:", error.message);
             } finally {
                 console.log("Fetch attempt finished.");
             }
         }
      
         fetchData();
      </script>
      </body>
      </html>
  3. Save the File.

  4. Open Developer Console (F12) to See the Logs.


Experiment

  1. Modify the URL to an invalid one and see if finally still executes.
  2. Add a loader (console.log("Loading...")) before the fetch call.
  3. Use finally to reset a variable after the request finishes.

Key Takeaways

  • finally executes after try and catch, regardless of the outcome.
  • It’s useful for cleanup operations like closing resources.
  • Helps maintain UI consistency (e.g., hiding loaders).