问题描述:

Here is what I mean.

If the browser natively supports fetch api (for example, Chrome), then it uses the native browser Promise.

If I use another Promise library, (like bluebird, for example), native fetch still isn't using it — it uses native Promise implementation instead.

Is there a way to override that?

Problem example:

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

fetch('/api')

.then(function (res) {

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

});

Why would I need that, you may be wondering? I wish to make use global rejection events which bluebird library supports and native Promises don't have.

网友答案:

You could use bluebird Promise.resolve() on the fetch promise. It will create a bluebird promise that assimilates fetch promise.

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

Create a promise that is resolved with the given value. If value is already a trusted Promise, it is returned as is. If value is not a thenable, a fulfilled Promise is returned with value as its fulfillment value. If value is a thenable (Promise-like object, like those returned by jQuery's $.ajax), returns a trusted Promise that assimilates the state of the thenable.

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

网友答案:

Here's some code that goes along the same line as @MinusFour suggested. Replace global with window if you're in a browser and not inside a module.

const fetch = global.fetch
global.fetch = function() {
    return Promise.resolve(fetch.apply(global, arguments))
}
相关阅读:
Top