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.
Clean-up after success or failure
Section titled “Clean-up after success or failure”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 onShowing Monthly reportSpinner offSpinner onError: Server unavailableSpinner offIn a web page, the console.log calls would be replaced by code that shows and hides the spinner element.
The result passes through
Section titled “The result passes through”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 undefinedthen() received 42A 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 filefinally() 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.