Performing cleanup with finally

suggest change

Promise.prototype.finally has been standard since ES2018. The callback runs whether the promise is fulfilled or rejected, like the finally clause of try.

You would usually use this functionality for cleanup:

let loadingData = true;

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

A Response has no data property; read the body with json() or text(). fetch rejects on network failure, not on an HTTP error status.

A normal return from finally is ignored. The chain keeps the previous fulfillment value or rejection reason, after waiting if the callback returns a promise. A throw, or a rejection from that promise, rejects the chain. In the example above, a successful processData(data) still fulfills the chain even though finally returns undefined.

Current engines provide finally. This polyfill covers a synchronous callback. It does not wait if callback returns a promise:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents