Skip to content

Instantly share code, notes, and snippets.

@batazo
Created February 20, 2021 22:47
Show Gist options
  • Select an option

  • Save batazo/c0fd0b66758680c5bdc35df07d24edb0 to your computer and use it in GitHub Desktop.

Select an option

Save batazo/c0fd0b66758680c5bdc35df07d24edb0 to your computer and use it in GitHub Desktop.
Fetch API promise chaining
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(pathToResource) // 1
.then(validateResponse) // 2
.then(readResponseAsJSON) // 3
.then(logResult) // 4
.catch(logError);
}
fetchJSON('examples/example.json');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment