Last active
August 13, 2022 16:15
-
-
Save DoctorDerek/2f478d7d2edc4228d6530ba36e591dd9 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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() | |
// When the request is loaded, call the callback function: | |
httpRequest.onload = function () { | |
callback(httpRequest.responseText) | |
} | |
httpRequest.open("GET", `${URL}${id}`) | |
httpRequest.send() | |
} | |
// A callback function is one passed to another function | |
function callback(result) { | |
const { name, status } = result ? JSON.parse(result) : {} | |
console.log(`${name} is ${status}`) | |
} | |
const fetchJerry = () => fetchCharacter(5) // Jerry has id 5. | |
fetchJerry() // Jerry Smith is Alive |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment