在处理异步请求时,我对如何创建和使用回调函数感到有些困惑。在线的所有示例都喜欢使用SetTimeout函数来模仿异步函数,但我想要一个仅使用真实世界API的示例。
我有一个异步函数,它接受一个邮政编码并返回一个像这样的JSON:
{
"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"
}
]
}
这是功能。 async函数转到API并返回上面的JSON。
sync函数只接受JSON并返回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();
};
以下代码流程不起作用,因为我没有使用回调。什么是最干净的执行这些功能的方式,以便我可以在所有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);
编辑:Bah,看起来这可能有答案:How do I return the response from an asynchronous call?
我仍然有兴趣知道如何用这个特殊的例子来做这件事。
答案 0 :(得分:1)
您必须将同步函数(cityToUpperCase
)作为参数传递给异步函数(returnLocationInfoByZip
),该函数将在调用onreadystatechange
时调用它:
var returnLocationInfoByZip = function(zip, callback){
...
client.onreadystatechange = function() {
if(client.readyState == 4) {
response = client.responseText;
callback(JSON.parse(response));
};
};
...
}
var cityToUpperCase = function(responseObject){
...
};
...
returnLocationInfoByZip(zip, function(responseObject){
console.log(cityToUpperCase(responseObject));
});