Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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))
@michaelnagy

This comment has been minimized.

Show comment
Hide comment
@michaelnagy

michaelnagy May 5, 2017

Hi, you also can write this function to a more concise way like this:
async function fetchAsync () {
let data = await (await fetch('https://api.github.com')).json();
return data;
}

michaelnagy commented May 5, 2017

Hi, you also can write this function to a more concise way like this:
async function fetchAsync () {
let data = await (await fetch('https://api.github.com')).json();
return data;
}

@kjkta

This comment has been minimized.

Show comment
Hide comment
@kjkta

kjkta May 9, 2017

@michaelnagy or use a fat arrow if you want to be fancy ;)

const fetchAsyncA = async () => 
	await (await fetch('https://api.github.com')).json()

kjkta commented May 9, 2017

@michaelnagy or use a fat arrow if you want to be fancy ;)

const fetchAsyncA = async () => 
	await (await fetch('https://api.github.com')).json()
@FilipIlievski

This comment has been minimized.

Show comment
Hide comment
@FilipIlievski

FilipIlievski Jul 20, 2017

Nice way to handle network requests, keeping everything in separate files:

RequestService.js

class RequestService {

// async function
async getRequest(url){
  let data = await (await (fetch(url)
    .then(res => {
      return res.json()
    })
    .catch(err => {
      console.log('Error: ', err)
    })
  ))
  return data
}
}

export default new RequestService()

NetwrokService.js

import RequestService from './RequestService'

const BASE_URL = "https://api.nytimes.com/svc"
const API_KEY = "?api-key=GET-YOUR-FREE-API-KEY:)"

class NetworkService {

  getArticles(){
    var url = `${BASE_URL}/search/v2/articlesearch.json${API_KEY}`
    return RequestService.getRequest(url)
  }

  getTopStories(){
    var url = `${BASE_URL}/topstories/v2/technology.json${API_KEY}`
    return RequestService.getRequest(url)
  }

}

export default new NetworkService()

ArticlesMain.js

.....
.....
_getDataStories(){
    NetworkService.getTopStories()
      .then(data => {
        console.log('Data:', data)
        this.setState({
          albumList: data.results
        })
      })
  }

  componentDidMount(){
     this._getDataStories()
  }

....
....

FilipIlievski commented Jul 20, 2017

Nice way to handle network requests, keeping everything in separate files:

RequestService.js

class RequestService {

// async function
async getRequest(url){
  let data = await (await (fetch(url)
    .then(res => {
      return res.json()
    })
    .catch(err => {
      console.log('Error: ', err)
    })
  ))
  return data
}
}

export default new RequestService()

NetwrokService.js

import RequestService from './RequestService'

const BASE_URL = "https://api.nytimes.com/svc"
const API_KEY = "?api-key=GET-YOUR-FREE-API-KEY:)"

class NetworkService {

  getArticles(){
    var url = `${BASE_URL}/search/v2/articlesearch.json${API_KEY}`
    return RequestService.getRequest(url)
  }

  getTopStories(){
    var url = `${BASE_URL}/topstories/v2/technology.json${API_KEY}`
    return RequestService.getRequest(url)
  }

}

export default new NetworkService()

ArticlesMain.js

.....
.....
_getDataStories(){
    NetworkService.getTopStories()
      .then(data => {
        console.log('Data:', data)
        this.setState({
          albumList: data.results
        })
      })
  }

  componentDidMount(){
     this._getDataStories()
  }

....
....
@kdichev

This comment has been minimized.

Show comment
Hide comment
@kdichev

kdichev Jul 27, 2017

@FilipIlievski why do you use promises in the RequestService class?

kdichev commented Jul 27, 2017

@FilipIlievski why do you use promises in the RequestService class?

@bob-bea-fre

This comment has been minimized.

Show comment
Hide comment
@bob-bea-fre

bob-bea-fre Sep 10, 2017

@msmfsd is there any need to assign and return data? This works just as well...

async function fetchAsync () {
  const response = await fetch('https://api.github.com');
  return await response.json();
}

@msmfsd is there any need to assign and return data? This works just as well...

async function fetchAsync () {
  const response = await fetch('https://api.github.com');
  return await response.json();
}
@gengns

This comment has been minimized.

Show comment
Hide comment
@gengns

gengns Sep 21, 2017

I came up to a similar use of fetch, but how are you dealing with errors?

async function async_fetch(url) {
  let response = await fetch(url)
  if (response.ok) return await response.json()
  throw new Error(response.status)
}

gengns commented Sep 21, 2017

I came up to a similar use of fetch, but how are you dealing with errors?

async function async_fetch(url) {
  let response = await fetch(url)
  if (response.ok) return await response.json()
  throw new Error(response.status)
}
@Clcll

This comment has been minimized.

Show comment
Hide comment
@Clcll

Clcll Oct 3, 2017

@gengns use try catch
try { let res = await fetch(url) } catch (e) { **_hangele Error here_** }

Clcll commented Oct 3, 2017

@gengns use try catch
try { let res = await fetch(url) } catch (e) { **_hangele Error here_** }

@halkeand

This comment has been minimized.

Show comment
Hide comment
@halkeand

halkeand Dec 15, 2017

Thanks for this gist, make me better understand async/await !

Thanks for this gist, make me better understand async/await !

@michaelpumo

This comment has been minimized.

Show comment
Hide comment
@michaelpumo

michaelpumo Dec 22, 2017

@FilipIlievski Found the Java guy! 👍

@FilipIlievski Found the Java guy! 👍

@j2is

This comment has been minimized.

Show comment
Hide comment
@j2is

j2is Dec 31, 2017

@FilipIlievski I like this solution. is there any reason to have an await inside of an await?

j2is commented Dec 31, 2017

@FilipIlievski I like this solution. is there any reason to have an await inside of an await?

@pacozaa

This comment has been minimized.

Show comment
Hide comment
@pacozaa

pacozaa Jan 5, 2018

@j2is from my understanding

  1. await number 1(the inner one), used to await fetch() function
  2. await number 2(the outter one), used to await res.json() function

Look at @kjkta answer might got you a clearer understanding in my humble opinion

Is that make sense?

Best,

pacozaa commented Jan 5, 2018

@j2is from my understanding

  1. await number 1(the inner one), used to await fetch() function
  2. await number 2(the outter one), used to await res.json() function

Look at @kjkta answer might got you a clearer understanding in my humble opinion

Is that make sense?

Best,

@Tevinthuku

This comment has been minimized.

Show comment
Hide comment
@Tevinthuku

Tevinthuku Mar 29, 2018

if You have 2 fetch calls, its better to await the value as compared to the fetch calls themselves, because we will then let the process occur in parallel other than in sequence
like so

   async function bestFetch() {
     const first = fetch();
    const two = fetch();
    const firstvalue = await first.json();
    const secondvalue = await two.json();
  }

Unlike the following ( below ) where the requests will happen in sequence
The second resource will only be fetched once the first request has been resolved

async function badFetch() {
     const first = await  fetch();
    const two = await  fetch();
    const firstvalue = await first.json();
    const secondvalue = await two.json();}

Tevinthuku commented Mar 29, 2018

if You have 2 fetch calls, its better to await the value as compared to the fetch calls themselves, because we will then let the process occur in parallel other than in sequence
like so

   async function bestFetch() {
     const first = fetch();
    const two = fetch();
    const firstvalue = await first.json();
    const secondvalue = await two.json();
  }

Unlike the following ( below ) where the requests will happen in sequence
The second resource will only be fetched once the first request has been resolved

async function badFetch() {
     const first = await  fetch();
    const two = await  fetch();
    const firstvalue = await first.json();
    const secondvalue = await two.json();}
@Dimon70007

This comment has been minimized.

Show comment
Hide comment
@Dimon70007

Dimon70007 Apr 17, 2018

thanks @Tevinthuku. The first example is awesome.

thanks @Tevinthuku. The first example is awesome.

@aminnairi

This comment has been minimized.

Show comment
Hide comment
@aminnairi

aminnairi May 11, 2018

Example that can be easily tested with JSONPlaceholder :

(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})`);
  }
})();

aminnairi commented May 11, 2018

Example that can be easily tested with JSONPlaceholder :

(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})`);
  }
})();
@ortonomy

This comment has been minimized.

Show comment
Hide comment

ortonomy commented Jul 5, 2018

@gengns gets it.

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