Skip to content

Instantly share code, notes, and snippets.

@mornir
Forked from msmfsd/es7-async-await.js
Last active December 13, 2017 17:28
Show Gist options
  • Save mornir/6bf64d8d41b8647b52b8f92e61c21cbc to your computer and use it in GitHub Desktop.
Save mornir/6bf64d8d41b8647b52b8f92e61c21cbc to your computer and use it in GitHub Desktop.
Javascript fetch JSON with ES7 Async Await
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