Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DoctorDerek/a4dcaa8a3c7c24fffdd35d1e5ad9e8e2 to your computer and use it in GitHub Desktop.
Save DoctorDerek/a4dcaa8a3c7c24fffdd35d1e5ad9e8e2 to your computer and use it in GitHub Desktop.
How To Return the Response From an Asynchronous Function in JavaScript https://medium.com/p/ecfcacef6138
// We'll query the Rick and Morty API using a GET request:
const URL = "https://rickandmortyapi.com/api/character/"
const fetchCharacter = async (id) => {
const response = await fetch(`${URL}${id}`)
return await response.json()
}
// Any function with an await keyword must be labeled async:
const fetchJerry = async () => await fetchCharacter(5)
const result = await fetchJerry() // We await the fetch call.
const { name, status } = result ? result : {}
console.log(`${name} is ${status}`) // Jerry Smith is Alive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment