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 aftertry
andcatch
, 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:
-
Create a File:
- Name it
lesson27-finally.html
.
- Name it
-
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>
-
-
Save the File.
-
Open Developer Console (
F12
) to See the Logs.
Experiment
- Modify the URL to an invalid one and see if
finally
still executes. - Add a loader (
console.log("Loading...")
) before the fetch call. - Use
finally
to reset a variable after the request finishes.
Key Takeaways
finally
executes aftertry
andcatch
, regardless of the outcome.- It’s useful for cleanup operations like closing resources.
- Helps maintain UI consistency (e.g., hiding loaders).