Skip to content

Instantly share code, notes, and snippets.

@mr-beerkiss
Created October 13, 2017 07:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mr-beerkiss/fc939c16ca9f9b4ab30d0d2d8f46f8fd to your computer and use it in GitHub Desktop.
Save mr-beerkiss/fc939c16ca9f9b4ab30d0d2d8f46f8fd to your computer and use it in GitHub Desktop.
Fetch Example
// I find MDN have the best resources for most JS stuff: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
// using async/await
(async function() {
// when using await, the function in the outer scope must be declared `async` otherwise it won't work and
// you'll get very mysterious error messages
try {
const response = await fetch('some/url');
// response.ok is generally a status code between 200 & 299
if (response.ok) {
let data;
if (response.headers.get('content-type') === 'application/json') {
// this is a convenience function that basically calls JSON.parse() on response.text(),
// so it saves you an extra step
data = await response.json();
} else {
data = await response.text();
}
console.log('Your data should be here', data);
} catch (err) {
console.error('remember to always deal with your errors!', err);
}
})();
// using promises
fetch(‘/some/url’)
.then(function(response) {
if (response.ok) {
if (response.headers.get('content-type') === 'application.json') {
// this returns a new promise so you need a new `.then()` to get the value
return response.json();
} else {
// as above this returns a new promise
return response.text();
}
}
})
.then(function(data) {
console.log('This should be the data you are expecting', data);
})
.catch(function(error) {
console.error('remember to always deal with your errors!', error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment