Skip to content

Instantly share code, notes, and snippets.

@marocas
Created February 5, 2020 11:00
Show Gist options
  • Select an option

  • Save marocas/b406dfe422f77b8c029604dc5e1a42b0 to your computer and use it in GitHub Desktop.

Select an option

Save marocas/b406dfe422f77b8c029604dc5e1a42b0 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))
@marocas

marocas commented Feb 5, 2020

Copy link
Copy Markdown
Author
(async () => {
  'use strict';
  console.clear();
  const getUser = async identifier => await (await fetch(`https://jsonplaceholder.typicode.com/users/${identifier}`)).json();
  try {
    const firstUser = await getUser(1);
    console.log(firstUser);
    const secondUser = await getUser(2);
    console.log(secondUser);
    // there are 10 users in JSONPlaceholder/Users
  } catch (exception) {
    console.error(`Failed to retrieve user informations: (${exception})`);
  }
})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment