Course contentsShow
← JavaScript
Lesson 1287 of 2,72329. PromisesFree lesson

Best Practices for Then/Catch/Finally

Understand idiomatic patterns: chain .then() for transformations, end with .catch() for errors, use .finally() for cleanup.

Best Practices for Then/Catch/Finally

You'll learn the idiomatic pattern for structuring promise chains that are readable, maintainable, and handle errors correctly.

The Golden Pattern

Think of promise chains like an assembly line: use .then() for transformations, end with .catch() for error handling, and use .finally() for cleanup. This creates a clear flow from success path to error handling to guaranteed cleanup.

Chain .then() for Transformations

Each .then() should focus on one transformation or operation. Return the transformed value or a new promise to keep the chain going:

fetchUser(id)
  .then(user => user.profile)
  .then(profile => profile.email)
  .then(email => sendEmail(email))

This reads like a story: get user, extract profile, extract email, send it.

End with .catch() for Errors

Place one .catch() at the end of your chain to handle any error from any step above it:

fetchUser(id)
  .then(user => user.profile)
  .then(profile => profile.email)
  .then(email => sendEmail(email))
  .catch(error => {
    console.error('Failed somewhere:', error);
  })

This catches errors from fetchUser, property access, or sendEmail. No need to scatter error handling throughout.

Use .finally() for Cleanup

Add .finally() after .catch() for operations that must happen regardless of success or failure:

showLoadingSpinner();

fetchUser(id)
  .then(user => displayUser(user))
  .catch(error => showErrorMessage(error))
  .finally(() => hideLoadingSpinner())

The spinner hides whether the request succeeds or fails—guaranteed.

Key Takeaway: Follow the pattern: chain .then() for steps → end with .catch() for errors → finish with .finally() for cleanup. This creates predictable, readable promise chains that handle all outcomes properly.