-1

I have a Javascript file where code is written in Javascript ES6 standards.The file is working fine in chrome but its not working in IE. After doing logs, I found out issue is in making ajax calls. Following code is where I am trying to make calls:

var response = await fetch(url, xhrRequestObject);
        if (response.ok) {
            var jsonResponse = await response.json();
            return jsonResponse;
        }

I googled through and found some polyfills to rectify this issue.But I am not getting how to use these polyfills inpure javascript file.

Any suggestions on how to use these polyfills in a pure js file ?

nip_sham
  • 59
  • 8

2 Answers2

4

I can't believe I didn't mention using Babel, see Marcel Gerber's answer for more on that.

But if you don't want to transpile:


Any fetch polyfill will have to provide or rely on a Promise polyfill. Then, since you're targeting IE, you can't use async functions and the await keyword because they were added in ES2018 and aren't supported by any version of IE.

So instead, you'd have to use promise syntax instead of await:

fetch(url, xhrRequestObject).
.then(function(response) {
    if (!response.ok) {
        throw new Error("HTTP error, status = " + response.status);
    }
    return reponse.json();
})
.then(function(data) {
    // ...use `data` here, it's the result of parsing the JSON
})
.catch(function(error) {
    // ...handle error here...
});

Or if you're returning this to a caller (your code suggests you might be):

return fetch(url, xhrRequestObject).
.then(function(response) {
    if (!response.ok) {
        throw new Error("HTTP error, status = " + response.status);
    }
    return reponse.json();
});

Note that the caller would need to handle errors on the promise that returns.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Fetch is not supported either in IE. So is there any way to use fetch polyfill in a pure js file to make fetch work in IE ? – nip_sham Nov 19 '18 at 06:47
  • @nip_sham - Yes, I referred to using a polyfill above. There are at least a couple of polyfills for `fetch`: https://duckduckgo.com/?q=fetch+polyfill – T.J. Crowder Nov 19 '18 at 08:01
  • @t.jcrowder I am not getting how to use these polyfills in my pure js file – nip_sham Nov 19 '18 at 08:15
3

It is not possible to polyfill new syntax features, like the "await" keyword you're using here.

Instead, your best bet is to use a transpiler like Babel. A transpiler takes your modern code and tries to make it executable in older browser versions. I'm not sure whether Babel supports async/await and if the transpiled code is executable in IE, though.