Performing cleanup with finally

suggest change

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;
        });
    };
}

Feedback about page:

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


Promises:
* Syntax
* Performing cleanup with finally

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
31 Promises
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde