Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kuldeepdaftary
Forked from msmfsd/es7-async-await.js
Created May 21, 2017 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuldeepdaftary/db3f3605a28567c1d8ad098ed3a4fa8d to your computer and use it in GitHub Desktop.
Save kuldeepdaftary/db3f3605a28567c1d8ad098ed3a4fa8d to your computer and use it in GitHub Desktop.
Javascript fetch JSON with ES7 Async Await
// Async/Await requirements: Latest Chrome/FF browser or Babel: https://babeljs.io/docs/plugins/transform-async-to-generator/
// Fetch requirements: Latest Chrome/FF browser or Github fetch polyfill: https://github.com/github/fetch
// async function
async function fetchAsync () {
// await response of fetch call
let response = await fetch('https://api.github.com');
// only proceed once promise is resolved
let data = await response.json();
// only proceed once second promise is resolved
return data;
}
// 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