10

The fetch api is really helpful but unfortunately it doesn't work for most browsers especially internet explorer. I tried to convert my code from es6 to es5 using babel but it doesn't solve this issue. It still includes fetch when it is converted to es5. How can I get around this issue. Here is the es6 code:

var btnText = document.getElementById('btnText');
var btnJson = document.getElementById('btnJson');
btnText.addEventListener("click",fetchBtnText);
function fetchBtnText() {
  fetch("sample.txt")
    .then((response) => response.text())
.then((data) => console.log(data))
}

Here is the conversion to es5

'use strict';
var btnText = document.getElementById('btnText');
var btnJson = document.getElementById('btnJson');
btnText.addEventListener("click", fetchBtnText);
function fetchBtnText() {
  fetch("sample.txt").then(function (response) {
    return response.text();
  }).then(function (data) {
    return console.log(data);
  });
}
Arty
  • 819
  • 3
  • 13
  • 24
The Star
  • 323
  • 4
  • 12

1 Answers1

6

You could use a polyfill, like this https://github.com/github/fetch

TKoL
  • 13,158
  • 3
  • 39
  • 73
  • 1
    Can you explain why it doesn't convert that. – Ishaan Mar 07 '20 at 09:13
  • 13
    @StukedCoder Babel is `mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments` as stated on their [home page](https://babeljs.io/docs/en/) and the Fetch API is not part of the ECMAScript/javascript language specification, but part of the Web APIs. See [here](https://stackoverflow.com/questions/44058726/is-the-fetch-api-an-ecmascript-feature) for more details. – Ahmed M Mar 13 '20 at 13:09