Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Promise redefinition does not affect promises returned by native functions

(See also this answer.)

When I redefine the Promise class (with a "monkey-patch" as shown below), this does not affect promises that are returned by a native function like fetch:

Promise = class extends Promise {
  constructor(executor) {
    console.log("Promise created");
    super(executor);
  }
}
console.log("Non-native promise");
Promise.resolve(1);
console.log("Native promise");
fetch("https://httpbin.org/delay/1");
console.log("Native promise");
document.hasStorageAccess();

When I run this snippet in the browser, the promise created by Promise.resolve uses the redefinition (so that "Promise created" is logged), but the promises returned by fetch or document.hasStorageAccess do not.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(When I try it in Node.js, fetch uses the redefinition, so it really depends on the implementation.)

I there a way to redefine Promise such that the redefinition is also used by native browser functions?

>Solution :

Native browser APIs are precompiled and operate independently of the JavaScript runtime’s global objects like Promise.

When you override Promise in JavaScript (e.g., window.Promise = …), it only affects the JavaScript environment. Native APIs continue to use their internal references, ignoring the overridden global Promise.

In your case, you will have to monkey-patch not only Promise, but also fetch or any other native API as a whole to achieve the intended result.

const originalFetch = window.fetch;
window.fetch = function(...args) {
  console.log("Fetch called with arguments:", args);
  const promise = originalFetch.apply(this, args);
  promise.then(
    (response) => console.log("Fetch promise resolved:", response),
    (error) => console.log("Fetch promise rejected:", error)
  );
  return promise;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading