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.
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.
It's certainly possible to reproduce the key features of the Axios library using the fetch() method provided by web browsers.
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.
Yes. Your code is fine. Except that after the second request, fetch(anotherUrl). then(function(response) { , I would replace return response.
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With