Skip to content

Instantly share code, notes, and snippets.

@arodu
Forked from robvolk/es6_fetch_example.js
Created January 14, 2019 16:52
Show Gist options
  • Save arodu/0643aec58b413323ab966ba5e7f85f4c to your computer and use it in GitHub Desktop.
Save arodu/0643aec58b413323ab966ba5e7f85f4c 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}`);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment