I'm a bit confused on how to create and use callback functions when working with async requests. All the examples online like to use a SetTimeout function to mimic an async function but I want an example that just uses a real world API.
I have an async function that takes a zip code and returns a JSON like this:
{
"post code": "90210",
"country": "United States",
"country abbreviation": "US",
"places": [
{
"place name": "Beverly Hills",
"longitude": "-118.4065",
"state": "California",
"state abbreviation": "CA",
"latitude": "34.0901"
}
]
}
Here are the functions. The async function goes to an API and returns the JSON above.
The sync function simply takes the JSON and returns the city string in UpperCase.
// Async Function
var returnLocationInfoByZip = function(zip){
var client = new XMLHttpRequest();
var response;
client.open("GET", "http://api.zippopotam.us/us/" + zip, true);
client.onreadystatechange = function() {
if(client.readyState == 4) {
response = client.responseText;
return response;
};
};
client.send();
};
// Sync Function
var cityToUpperCase = function(responseObject){
var city = responseObject.places[0]["place name"];
return city.toUpperCase();
};
The following code flow doesn't work because I'm not utilizing callbacks. What would be the cleanest-looking way to execute these functions so I could get the desired console log of the city name in all UpperCase?
// Obviously doesn't work
var zip = "94043";
var responseObject = returnLocationInfoByZip(zip);
//Here I would like to console log the uppercase city name
var cityInUpperCase = cityToUpperCase(responseObject);
console.log(cityInUpperCase);
EDIT: Bah, looks like this might have an answer: How do I return the response from an asynchronous call?
I'd still be interested to know how to do it with this particular example of mine though.