是否可以覆盖本机获取 API 以使用所需的承诺库而不是本机浏览器承诺

Is it possible to override native fetch api to use a desired Promise library instead of native browser Promise?

本文关键字:承诺 本机 浏览器 覆盖 获取 API 是否      更新时间:2023-09-26

这就是我的意思。

如果浏览器原生支持 fetch api(例如 Chrome),则它使用原生浏览器 Promise .

如果我使用另一个 Promise 库(例如蓝鸟),原生fetch仍然没有使用它——它使用原生Promise实现。

有没有办法覆盖它?

问题示例:

window.Promise = function () { return null; };

fetch('/api')
.then(function (res) {
    console.log('fetch result!', res); // still works because it uses native Promise
});

为什么我需要那个,你可能想知道?我希望利用bluebird库支持和本机承诺所没有的全局拒绝事件。

下面是一些与@MinusFour建议相同的代码。如果您使用的是浏览器而不是模块内部,请将global替换为window

const fetch = global.fetch
global.fetch = function() {
    return Promise.resolve(fetch.apply(global, arguments))
}

你可以在fetch承诺上使用蓝鸟Promise.resolve()。它将创造一个蓝鸟的承诺,吸收fetch承诺。

Promise.resolve(Promise|any value) -> Promise

创建一个使用给定值解析的承诺。如果 value 已经是受信任的 Promise,则按原样返回。如果值不是当时可取的,则返回已履行的承诺,并将值作为其履行值。如果 value 是一个可 thenable(类似 Promise 的对象,如 jQuery 的 $.ajax 返回的对象),则返回一个受信任的 Promise,该 Promise 吸收了 thenable 的状态。

http://bluebirdjs.com/docs/api/promise.resolve.html

我也

发现了这个,并认为在这里发布它可能是有意义的 -https://github.com/github/fetch/issues/417

帖子说(如果链接断开)-如果你想在浏览器中使用蓝鸟,请使用这个,和

window.fetch = null

窗。承诺=蓝鸟

require('whatwg-fetch') 最新版本的浏览器可能有 fetch API 如果有获取 API,此存储库将返回 false。

如果你想在 Node 中使用 Bluebird,请使用 node-fetch,以及

let fetch = require('node-fetch');

获取。承诺=蓝鸟