gengns ES

An entry from the gengns log, written by Génesis García Morilla · · JavaScript

Asynchronous fetch

Using fetch with asyncronous functions.

Result of the demo “Asynchronous fetch”

JavaScript

$div_ = document.querySelector('div')

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

async_fetch('https://httpbin.org/ip')
  .then(data => $div_.textContent = JSON.stringify(data))
  .catch(error => alert(error))

HTML

<div></div>
Open in JSFiddle

This way is even cleaner than using fetch by its own, check this out!

Tags: AJAX, async, await, fetch, get, JSON, promises