Search code examples
javascriptecmascript-6es6-promise

Is it possible to overwrite native Es6 promise resolve method?


I know that it's not the best approach to overwrite native JS API and I do it more for experiment.

I would like to overwrite Promise resolve method handler to do some extra logic on each resolve. Is it possible?


Solution

  • Yes, it's possible. You have to wrap Promise.prototype.then method.

    Promise.prototype.then = (oldThen=>{
        return function then(_successHandler, _rejectHandler){
            /* your logic here; 
            remember: both successHandler and rejectHandler can be non-functions */
            return oldThen.call(this, wrappedSuccessHandler, wrappedRejectHandler);
        }
    })(Promise.prototype.then);
    

    This code won't be able to intercept new Promise() calls, but there is other workaround for this:

    class SubPromise extends Promise {
        constructor(executor) {
            super(function(_resolve, _reject) {
               /* your code goes here */
               return executor(wrappedResolve, wrappedReject);
            });
        }
    
        then(success, reject) {
            return super.then(wrappedSuccessHandler, wrappedRejectHandler);
        }
    }
    window.Promise = SubPromise;
    

    It replaces global Promise property with your implementation, so all subsequent calls resolving to window.Promise will return your implementation.

    See 25.4.5.3 Promise.prototype.then in spec for further details (with default handlers "thrower" and "identity").