Created
February 20, 2021 22:47
-
-
Save batazo/c0fd0b66758680c5bdc35df07d24edb0 to your computer and use it in GitHub Desktop.
Fetch API promise chaining
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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