javascript - Executing async functions with a callback? -
I am a little confused about how to create and use callback functions while working with async requests. All examples are online as an async function.
I have an async function that takes a zip code and returns a JSON like this:
{"post code": "90210", "country": "United States": "State": "America", "Location": [["Location name": "Beverly Hills", "Longitude": "-118.4065", "State": "California", "State abbreviation Name ":" CA "," Latitude ":" 34.0901 "}}}
These functions go to the Async function API and give up JSON.
Just takes JSON in the sync function and returns the city's string to the upper seas
// async Function var ReturnLocationInfoByZip = function (zip) {var client = new XMLHttpRequest (); Miscellaneous feedback; 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 city toupper onCase = function (reaction object) {var city = response object.place [0] ["name of place"]; return city. Uppercase ();};
The following code flow does not work because I call I'm not using back. What would be the most obvious way of executing these tasks, so that I can get the desired console log in the name of the city in all uppercase?
// obviously not var zip = "94043"; Var responseobox = return location: Infobjip (zip); // Here I want to console the upper case city name to var cityInUpperCase = cityToUpperCase (responseObject); Console.log (cityInUpperCase); Edit: Bah, it seems that the answer may be: I still would be interested in knowing how to do this with this example Though.
You have to pass the sync function ( cityToUpperCase
) as a parameter Async function ( returnLocationInfoByZip
) will apply when it is called onreadystatechange
:
var returnLocationInfoByZip = function (zip, callback) {. .. client.onreadystatechange = function () {if (client.readyState == 4) {response = client.responseText; Callback (json.parse); }; }; ...} var cityToUpperCase = functionObject {...}; ... Back to location location InfoByZip (zip, function (feedback object) {console.log (cityToUpperCase (responseObject))});
Comments
Post a Comment