ES6 promise settled callback?

Isn’t there a .always like jQuery has?

No, there’s not (yet). Though there is an active proposal, so maybe ES2018.
Yes, there is: promise .finally() is part of the standard since ES2018.

If not, how do I achieve this?

You can implement the finally method yourself like this:

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

or more extensively, with passing resolution information to the callback:

Promise.prototype.finally = function(cb) {
    const res = () => this
    return this.then(value =>
        Promise.resolve(cb({state:"fulfilled", value})).then(res)
    , reason =>
        Promise.resolve(cb({state:"rejected", reason})).then(res)
    );
};

Both ensure that the original resolution is sustained (when there is no exception in the callback) and that promises are awaited.

Leave a Comment