Promise.prototype.done

Time:2021-8-10

The promise design specification does not specify promise.prototype.done, so you can use the implementation provided by the existing class library or implement it yourself.

effect

No matter whether the callback chain of promise object ends with then method or catch, as long as the last method throws an error, it may not be caught (because the error inside promise will not bubble to the global). Therefore, it is necessary to provide a done method, which is always at the end of the callback chain (executed) to ensure that any possible error is thrown;

Sample code

"use strict";
if (typeof Promise.prototype.done === "undefined") {
    Promise.prototype.done = function (onFulfilled, onRejected) {
        this.then(onFulfilled, onRejected).catch(function (error) {
            setTimeout(function () {
                throw error;
            }, 0);
        });
    };
}

Done has the following two characteristics

1. Errors in done are thrown as exceptions
2. Terminate promise chain