Skip to content

Instantly share code, notes, and snippets.

@pinkhominid
Created February 11, 2019 15:43
Show Gist options
  • Save pinkhominid/c1a09f74caf771eec6ea1121b317fc7c to your computer and use it in GitHub Desktop.
Save pinkhominid/c1a09f74caf771eec6ea1121b317fc7c to your computer and use it in GitHub Desktop.
Clean Fetch Example (per Google Devs)
function logResult(result) {
console.log(result);
}
function logError(error) {
console.log('Looks like there was a problem: \n', error);
}
function validateResponse(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
function readResponseAsJSON(response) {
return response.json();
}
function fetchJSON(pathToResource) {
fetch(pathToResourcei, {cache: 'no-store'})
.then(validateResponse)
.then(readResponseAsJSON)
.then(logResult)
.catch(logError);
}
fetchJSON('examples/example.json');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment