Promise.prototype.finally() in JavaScript

🔚 What is finally()?

The finally() method is available on all Promises. It allows you to run code after a promise settles (regardless of whether it was fulfilled or rejected).

>>“Always clean up, no matter the outcome.”

📦 Syntax

Code Snippet

promise
  .then((result) => {
    // Handle success
  })
  .catch((error) => {
    // Handle failure
  })
  .finally(() => {
    // Runs no matter what
  });

🚀 Example: Success

Running cleanup on success

fetch("https://api.example.com/data")
  .then((res) => res.json())
  .then((data) => {
    console.log("✅ Got data:", data);
  })
  .catch((err) => {
    console.error("❌ Error:", err);
  })
  .finally(() => {
    console.log("🔚 Done fetching");
  });

🚨 Example: Failure

Runs even when rejected

Promise.reject("Something went wrong")
  .catch((err) => {
    console.error("❌ Error caught:", err);
  })
  .finally(() => {
    console.log("🔚 Cleanup after error");
  });

🧼 Use Case: Cleanup

finally() is ideal for things like:

  • 🔐 Hiding loading spinners
  • 🧹 Releasing resources
  • 🛑 Canceling timers

🤔 What not to use finally() for?

Do not rely on the return value of finally() to affect the promise chain. It doesn’t receive the resolved/rejected value and can’t modify it.

Code Snippet

Promise.resolve("OK")
  .finally(() => {
    return "Overridden"; // ❌ Ignored
  })
  .then((value) => {
    console.log(value); // 👉 "OK", not "Overridden"
  });

📚 Summary

  • finally() runs on both resolve and reject
  • Useful for shared post-processing or cleanup tasks
  • Does not modify the promise result

🔗 References

>>“Whether it works or fails — do the dishes.”