-
-
Save mornir/6bf64d8d41b8647b52b8f92e61c21cbc to your computer and use it in GitHub Desktop.
Javascript fetch JSON with ES7 Async Await
This file contains 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
async function fetchAsync () { | |
// await response of fetch call | |
const response = await fetch('https://api.github.com'); | |
// only proceed once promise is resolved | |
const data = await response.json(); | |
// only proceed once second promise is resolved | |
return data; | |
} | |
// more concise | |
async function fetchAsync () { | |
// await response of fetch call | |
const response = await fetch('https://api.github.com'); | |
// only proceed once promise is resolved | |
return response.json(); | |
} | |
/* | |
Inside an async function, return await is useless. | |
Since the return value of an async function is always wrapped in Promise.resolve, | |
return await doesn't actually do anything except add extra time before the overarching | |
https://jakearchibald.com/2017/await-vs-return-vs-return-await/ | |
https://github.com/eslint/eslint/blob/master/docs/rules/no-return-await.md | |
*/ | |
// trigger async function | |
// log response or catch error of fetch promise | |
fetchAsync() | |
.then(data => console.log(data)) | |
.catch(reason => console.log(reason.message)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment