Promise.prototype.finally()

Registers a function that runs once the promise settles, whether it ends in success or failure.

Returns
A new promise with the same result or error as the original.
On this page

Example

#
JavaScript
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms))

let loading = true
console.log('Loading:', loading)

wait(300, ['Lesson 1', 'Lesson 2'])
  .then((lessons) => console.log('Lessons:', lessons))
  .catch((error) => console.log('Error:', error.message))
  .finally(() => {
    loading = false
    console.log('Loading:', loading)
  })
Console
Loading: true
Lessons: ['Lesson 1', 'Lesson 2']
Loading: false

Definition and usage

#

The finally() method takes a function with no arguments that always runs once the promise stops being pending: after fulfillment and after rejection. It’s a good place for cleanup, such as hiding a loading indicator or re-enabling a button.

The function in finally() receives neither the result nor the error, and doesn’t change the chain’s value. The result or error passes through it unchanged, so the following then() and catch() calls behave as if it weren’t there.

There’s one exception: if the function in finally() throws an error or returns a rejected promise, that new error replaces the original result.

Syntax

#
Syntax
promise.finally(onFinally)

Parameters

#
  • onFinally

    function ()

    The function called after the promise is fulfilled or rejected. It receives no arguments.

More examples

#
The result and error pass through finally()
JavaScript
const value = await Promise.resolve(42).finally(() => 'this value is ignored')
console.log(value)

try {
  await Promise.reject(new Error('Server is not responding')).finally(() => {
    console.log('Cleaning up after the error')
  })
} catch (error) {
  console.log(error.message)
}
Console
42
Cleaning up after the error
Server is not responding

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Use finally() for cleanup that must always run: turning off a loading indicator, closing a connection, re-enabling a form.
  • Don’t return a value from finally() that you’re relying on. It will be ignored.
  • In code using await, the equivalent is the finally block in a try...catch...finally construct.

Related entries

#

Spotted a mistake or missing an example? Write to us.