mpen mpen - 3 months ago 19
Javascript Question

ES6 promise settled callback?

I want to run the same action whether my Promise resolved successfully or not. I don't want to bind the same function to both args of

.then
. Isn't there a
.always
like jQuery has? If not, how do I achieve this?

Answer

Isn't there a .always like jQuery has?

No, there's not (yet).

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.