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.
Example
#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)
})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
#promise.finally(onFinally)Parameters
#onFinally
function ()
The function called after the promise is fulfilled or rejected. It receives no arguments.
More examples
#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)
}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 thefinallyblock in atry...catch...finallyconstruct.
Related entries
#- Promise.prototype.then()Registers a function to run when the promise is fulfilled, and returns a new promise so you can chain steps together.
- Promise.prototype.catch()Registers an error-handling function that runs when the promise is rejected.
- try...catchCatches errors thrown in the try block and handles them in catch. The optional finally always runs.
- PromiseAn object representing the result of an operation that will be available in the future: a value on success or an error.
Spotted a mistake or missing an example? Write to us.