Promise 重新定义不会影响原生函数返回的 Promise

问题描述 投票:0回答:1

(另请参阅此答案。)

当我重新定义

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
,这样重新定义也可以被本机浏览器功能使用吗?

javascript browser promise
1个回答
1
投票

[是否]有办法重新定义

Promise
,以便本机浏览器功能也使用重新定义?

不,没有。您可以做的事情包括:

  • 改变

    Promise.prototype

  • 用返回您的 Promise 类型的包装器替换返回本机 Promise 的函数

© www.soinside.com 2019 - 2024. All rights reserved.