是否可以覆盖本机 fetch api 以使用所需的 Promise 库而不是本机浏览器 Promise?

tim*_*der 5 javascript error-handling onerror es6-promise fetch-api

这就是我的意思。

如果浏览器本机支持fetch api(例如,Chrome),则它使用本机浏览器Promise

如果我使用另一个 Promise 库(例如bluebird), nativefetch仍然没有使用它——而是使用 nativePromise实现。

有没有办法覆盖它?

问题示例:

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


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

为什么我需要那个,你可能想知道?我希望利用全球排斥事件,其bluebird库支持和原生的承诺不具备的。

Ric*_*tte 5

下面是一些与 @MinusFour 建议的代码相同的代码。如果您在浏览器中而不是在模块内,请替换为globalwindow

const fetch = global.fetch
global.fetch = function() {
    return Promise.resolve(fetch.apply(global, arguments))
}
Run Code Online (Sandbox Code Playgroud)


Min*_*our 3

Promise.resolve()你可以在承诺上使用蓝鸟fetch。它将创建一个同化fetch承诺的蓝鸟承诺。

Promise.resolve(Promise|任意值) -> Promise

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

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