Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 904
timetowonder Avatar asked Feb 12 '16 16:02

timetowonder


People also ask

Is fetch supported in all browsers?

Google ChromeChrome version 4 to 39 does not support Fetch. Chrome 40 to 41 partially supportsFetchAvailable in Chrome and Opera within Window and Workers by enabling the 'Experimental Web Platform Features' flag in chrome://flags. Chrome 42 to 67 supports Fetchproperty.

Which library does the fetch () function come from?

It's certainly possible to reproduce the key features of the Axios library using the fetch() method provided by web browsers.

What mandatory argument does the fetch () method take?

The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise that resolves to the Response to that request — as soon as the server responds with headers — even if the server response is an HTTP error status.

Can you fetch inside a fetch?

Yes. Your code is fine. Except that after the second request, fetch(anotherUrl). then(function(response) { , I would replace return response.


1 Answers

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))
}
like image 111
Richard Ayotte Avatar answered Oct 29 '22 18:10

Richard Ayotte