2014-10-28 135 views
-1

我在處理異步請求時如何創建和使用回調函數有點困惑。在線的所有示例都喜歡使用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" 
     } 
    ] 
} 

下面是功能。異步函數轉到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); 

編輯:呸,看起來這可能有一個答案:How do I return the response from an asynchronous call?

我仍然有興趣知道如何使用我的這個特殊的例子做雖然。

回答

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)); 
}); 
+0

'responseObject'是不確定的。 – 2014-10-28 08:53:43

+0

是的,'responseObject'是未定義的。 http://jsfiddle.net/8Lr8hx40/ – fuzzybabybunny 2014-10-28 09:17:35

+0

什麼......爲什麼第10行的警報不起作用? http://jsfiddle.net/8Lr8hx40/1/ – fuzzybabybunny 2014-10-28 09:31:13