Skip to content

Promises - Finally Method

finally() adds a callback that runs when a promise settles, whether it was fulfilled or rejected. It is the place for clean-up that must happen either way, such as hiding a loading spinner, re-enabling a button or closing a connection. Without it, the same line would have to appear in both the then() and the catch() callbacks.

This example turns a spinner on before loading a report and off again afterwards. The first load succeeds and the second fails:

const loadReport = (shouldFail) =>
new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldFail) {
reject(new Error('Server unavailable'));
} else {
resolve('Monthly report');
}
}, 100);
});
const showReport = (shouldFail) => {
console.log('Spinner on');
return loadReport(shouldFail)
.then((report) => console.log('Showing', report))
.catch((error) => console.log('Error:', error.message))
.finally(() => console.log('Spinner off'));
};
showReport(false).then(() => showReport(true));

This prints:

Spinner on
Showing Monthly report
Spinner off
Spinner on
Error: Server unavailable
Spinner off

In a web page, the console.log calls would be replaced by code that shows and hides the spinner element.

The finally() callback receives no argument, because it is not meant to care whether the promise succeeded. Its return value is ignored too, so the original value carries on down the chain:

Promise.resolve(42)
.finally((argument) => {
console.log('finally() received', argument);
return 'ignored';
})
.then((value) => console.log('then() received', value));

This prints:

finally() received undefined
then() received 42

A rejection passes through in the same way, so a catch() placed after finally() still receives the original error.

Pitfall: an error in finally() replaces the result

Section titled “Pitfall: an error in finally() replaces the result”

If the finally() callback throws, or returns a promise that is rejected, the chain is rejected with that new error, and the original result is lost:

Promise.resolve('Saved')
.finally(() => {
throw new Error('Could not close the file');
})
.then((value) => console.log(value))
.catch((error) => console.log('Failed:', error.message));

This prints:

Failed: Could not close the file

finally() was added in ES2018. In an async function, a try...finally block does the same job, as shown in Async/Await combined with Promises.

Steve Griffith covers this topic in his video Practical Uses for Promise finally.