What is the equivalent of Bluebird Promise.finally in native ES6 promises? [duplicate]

Bluebird offers a finally method that is being called whatever happens in your promise chain. I find it very handy for cleaning purposes (like unlocking a resource, hiding a loader, ...)

Is there an equivalent in ES6 native promises?


As of February 7, 2018

Chrome 63+, Firefox 58+, and Opera 50+ support Promise.finally.

In Node.js 8.1.4+ (V8 5.8+), the feature is available behind the flag --harmony-promise-finally.

The Promise.prototype.finally ECMAScript Proposal is currently in stage 3 of the TC39 process.

In the meantime to have promise.finally functionality in all browsers; you can add an additional then() after the catch() to always invoke that callback.

Example:

myES6Promise.then(() => console.log('Resolved'))
            .catch(() => console.log('Failed'))
            .then(() => console.log('Always run this'));

JSFiddle Demo: https://jsfiddle.net/9frfjcsg/

Or you can extend the prototype to include a finally() method (not recommended):

Promise.prototype.finally = function(cb) {
    const res = () => this;
    const fin = () => Promise.resolve(cb()).then(res);
    return this.then(fin, fin);
};

JSFiddle Demo: https://jsfiddle.net/c67a6ss0/1/

There's also the Promise.prototype.finally shim library.