CodeBlanks Logo Icon CodeBlanks

Cleanup with finally

JavaScript course · Intermediate · Lesson 75/134

Learn finally for cleanup that runs whether the promise succeeded or failed.

Cleanup with finally

finally always runs when the promise settles, whether it fulfilled or rejected. It takes no parameter, because it cannot see the value. It is used only for cleanup: hiding a spinner, closing a file and so on.

loadOrder()
  .then(order => console.log(order))
  .catch(error => console.log(error))
  .finally(() => hideSpinner());

finally does not break the chain; the returned value passes to the next step. That is why it is added as the last step.

When do you use finally?

finally is most often used in two cases. First, to hide a loading spinner whether the work succeeded or failed. Second, to reset the interface after a network request finishes.

showSpinner();
loadOrder()
  .finally(() => hideSpinner());

The key point: finally does not catch errors, it only cleans up side effects. Error handling belongs to catch, cleanup belongs to finally.

Exercise A then, catch and finally chain

fetchReport returns a promise. Call fetchReport and build a chain: in then log the report with console.log; in catch log the error with console.log; in finally call hideSpinner.

Show example solution
fetchReport()
  .then(report => console.log(report))
  .catch(error => console.log(error))
  .finally(() => hideSpinner());

Test yourself

  1. What is passed as a parameter to finally?

    • No parameter
    • The resolved value
    • The rejection reason
    • The promise object
    Show answer

    No parameter — Correct! finally takes no parameter; it only does cleanup.

  2. Add finally to the chain

    loadOrder()
      .then(order => console.log(order))
      .____(() => hideSpinner());
    Show answer
    loadOrder()
      .then(order => console.log(order))
      .finally(() => hideSpinner());
  3. Match the three methods

    then
    Handles success
    catch
    Handles failure
    finally
    Runs in both cases

All lessons in Intermediate