Explain the callback Promise.finally in JavaScript

The Promise.finally() method executes a callback function when a promise settles, regardless of whether it's fulfilled or rejected. This method is essential for cleanup operations and tasks that must run after promise completion.

Syntax

promise.finally(callback)

Parameters

callback: A function that executes when the promise settles. It receives no arguments and its return value is ignored.

How It Works

Unlike .then() and .catch(), the finally callback doesn't receive the promise's result or rejection reason. It simply indicates that the promise has completed.

Example with Fetch API

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise.finally Example</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
        }
        .result {
            font-size: 18px;
            font-weight: 500;
            margin: 10px 0;
        }
        button {
            padding: 10px 15px;
            font-size: 16px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Promise.finally in JavaScript</h1>
    <div class="result" id="status">Ready to fetch data...</div>
    <div class="result" id="data"></div>
    <button onclick="fetchData()">Fetch User Data</button>
    
    <script>
        function fetchData() {
            const statusEl = document.getElementById('status');
            const dataEl = document.getElementById('data');
            
            statusEl.innerHTML = 'Loading...';
            dataEl.innerHTML = '';
            
            fetch('https://jsonplaceholder.typicode.com/users/1')
                .then(response => response.json())
                .then(user => {
                    dataEl.innerHTML = `<strong>User:</strong> ${user.name} (${user.email})`;
                })
                .catch(error => {
                    dataEl.innerHTML = `<span style="color: red;">Error: ${error.message}</span>`;
                })
                .finally(() => {
                    statusEl.innerHTML = 'Request completed!';
                    console.log('Promise finished - cleanup operations can go here');
                });
        }
    </script>
</body>
</html>

Example with Both Success and Error Cases

// Simulating successful promise
const successPromise = new Promise((resolve) => {
    setTimeout(() => resolve("Success!"), 1000);
});

successPromise
    .then(result => console.log("Result:", result))
    .catch(error => console.log("Error:", error))
    .finally(() => console.log("Success promise completed"));

// Simulating failed promise
const failPromise = new Promise((resolve, reject) => {
    setTimeout(() => reject(new Error("Something went wrong")), 1000);
});

failPromise
    .then(result => console.log("Result:", result))
    .catch(error => console.log("Error:", error.message))
    .finally(() => console.log("Fail promise completed"));
Result: Success!
Success promise completed
Error: Something went wrong
Fail promise completed

Common Use Cases

  • Loading indicators: Hide spinners after API calls
  • Resource cleanup: Close connections or clear timeouts
  • Logging: Record completion regardless of outcome
  • UI updates: Re-enable buttons or reset forms

Key Points

  • finally() runs after both then() and catch()
  • The callback receives no arguments
  • The return value is generally ignored
  • Perfect for cleanup operations that must always execute

Conclusion

Promise.finally() ensures critical cleanup code runs regardless of promise outcome. Use it for operations like hiding loading indicators, closing resources, or logging completion status.

Updated on: 2026-03-15T23:18:59+05:30

254 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements