Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DoctorDerek/cf07e0bbda9173517e388975df3c68b2 to your computer and use it in GitHub Desktop.
Save DoctorDerek/cf07e0bbda9173517e388975df3c68b2 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 = (id) => {
const httpRequest = new XMLHttpRequest()
httpRequest.open("GET", `${URL}${id}`)
httpRequest.send()
return httpRequest.responseText
}
const fetchJerry = () => fetchCharacter(5) // Jerry has id 5.
const result = fetchJerry() // The result is always undefined.
const { name, status } = result ? JSON.parse(result) : {}
console.log(`${name} is ${status}`) // undefined is undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment