6

I want to override the Promise constructor and the then method in Promise. So, whenever someone creates a new Promise object, first my code will be executed and then the original promise constructor will get called.

Similarly, when someone calls .then function of Promise, first my code will get executed and then the callback of then function will get executed.

I tried this

var bind = Function.bind;
var unbind = bind.bind(bind);

function instantiate(constructor, args) {
    return new (unbind(constructor, null).apply(null, args));
}

var oldProto = Promise.prototype;
Promise = function() {
    console.log("Promise instantiated");
    var promise = instantiate(Promise, arguments);
    return promise;
};
Promise.prototype = oldProto;

While calling this using

var myFirstPromise = new Promise((resolve, reject) => {
  setTimeout(function(){
    resolve("Success!"); // Yay! Everything went well!
  }, 250);
});

myFirstPromise.then((successMessage) => {
  console.log("Yay! " + successMessage);
});

It led to infinite loop with console filled up with Promise instantiated log. I also tried the following:

Promise = function(Promise) {
    MyPromise.prototype = Promise.prototype;

    function MyPromise(){
        console.log("Hello");
        var promise = Function.prototype.bind.apply(MyPromise, arguments);
        console.log(promise);
        return promise;
    }
}(Promise);

But, I am not sure whether the constructor overriden is the correct way to do it and how to define the then function for Promise.

Yairopro
  • 9,084
  • 6
  • 44
  • 51
skjindal93
  • 706
  • 1
  • 16
  • 34
  • https://stackoverflow.com/questions/48158730/extend-javascript-promise-and-resolve-or-reject-it-inside-constructor/48159603 – Tiberiu C. Jan 30 '22 at 04:30

0 Answers0