Created
June 14, 2018 17:34
-
-
Save Ormadont/313e2d4dfb9fa27237f8904c12c18be2 to your computer and use it in GitHub Desktop.
boilerplate code: async GET Requests
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
//boilerplate code: async GET Requests | |
//The async keyword will ensure that the function returns a promise. | |
const getData = async () => { | |
try { | |
const response = await fetch('https://api-to-call.com/endpoint'); | |
if (response.ok) { | |
//Since .json() is an asynchronous method we have to await until the promise status is resolved. Then we store the value to know what data the JSON holds. | |
const jsonResponse = await response.json(); | |
return jsonResponse; | |
} | |
throw new Error('Request failed!'); | |
} | |
catch(error) { | |
console.log(error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment