How to use fetch with Async, Await in JavaScript?

The fetch API is very flexible to fetch resources. We can get resources through network too.

The fetch API returns a Promise based on the success or failure of the request. If we are okay to use then chain to get the response from fetch we can do the following approach:

  var requestOptions = {
    method: 'GET',
    redirect: 'follow'
  };

  fetch("https://api.github.com/users/berozapaul", requestOptions)
      .then(response => response.json())
      .then(result => console.log(result))
      .catch(error => console.log('error', error));

But we want to avoid then chain get the fetch response in an imperative way we can use async and await. Following is the code segment to use async await together.

  var requestOptions = {
    method: 'GET',
    redirect: 'follow'
  };

  (async() => {
    const response = await fetch("https://api.github.com/users/berozapaul", requestOptions);
    const json = await response.json();
    console.log(json);
  })();
Share