Skip to content

Instantly share code, notes, and snippets.

@robvolk
Last active October 17, 2019 16:46
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save robvolk/99057492b8fd4d7d574bd89e4bde9f3b to your computer and use it in GitHub Desktop.
Save robvolk/99057492b8fd4d7d574bd89e4bde9f3b to your computer and use it in GitHub Desktop.
AJAX requests in ES6 using fetch()
// ES6 Fetch docs
// https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('https://some.url.com')
.then(response => {
if (response.ok) {
return Promise.resolve(response);
}
else {
return Promise.reject(new Error('Failed to load'));
}
})
.then(response => response.json()) // parse response as JSON
.then(data => {
// success
})
.catch(function(error) {
console.log(`Error: ${error.message}`);
});
});
@aquesadagt
Copy link

Thank you!
It was really useful!

Just one question:
Do we really need the last
});
?

@hunkjazz
Copy link

hunkjazz commented Dec 1, 2018

@aquesadagt There is no need for these last characters. Probably, a typo.

@rajeshkumaryadavdotcom
Copy link

Is it IE compatible?

@robvolk
Copy link
Author

robvolk commented Oct 17, 2019

I don't know, you'll have to try it. I'd imagine you'll need a polyfill to get that to work with older browsers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment