JavaScript Promises Performing cleanup with finally()


Example

There is currently a proposal (not yet part of the ECMAScript standard) to add a finally callback to promises that will be executed regardless of whether the promise is fulfilled or rejected. Semantically, this is similar to the finally clause of the try block.

You would usually use this functionality for cleanup:

var loadingData = true;

fetch('/data')
    .then(result => processData(result.data))
    .catch(error => console.error(error))
    .finally(() => {
        loadingData = false;
    });

It is important to note that the finally callback doesn't affect the state of the promise. It doesn't matter what value it returns, the promise stays in the fulfilled/rejected state that it had before. So in the example above the promise will be resolved with the return value of processData(result.data) even though the finally callback returned undefined.

With the standardization process still being in progress, your promises implementation most likely won't support finally callbacks out of the box. For synchronous callbacks you can add this functionality with a polyfill however:

if (!Promise.prototype.finally) {
    Promise.prototype.finally = function(callback) {
        return this.then(result => {
            callback();
            return result;
        }, error => {
            callback();
            throw error;
        });
    };
}