(另请参阅此答案。)
当我重新定义
Promise
类(使用“猴子补丁”,如下所示)时,这不会影响像 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();
当我在浏览器中运行此代码片段时,
Promise.resolve
创建的 Promise 使用重新定义(以便记录“Promise 创建”),但 fetch
或 document.hasStorageAccess
返回的 Promise 则不会。
(当我在 Node.js 中尝试时,
fetch
使用重新定义,所以这实际上取决于实现。)
我有办法重新定义
Promise
,这样重新定义也可以被本机浏览器功能使用吗?
[是否]有办法重新定义
,以便本机浏览器功能也使用重新定义?Promise
不,没有。您可以做的事情包括:
改变
Promise.prototype
用返回您的 Promise 类型的包装器替换返回本机 Promise 的函数