2012-06-09 41 views
0

值我的代碼:返回從函數的CoffeeScript

country: (origin) -> 
    @geocoder = new google.maps.Geocoder 
    @geocoder.geocode(
     'latLng': origin, 
     (results, status) => 
      if status is google.maps.GeocoderStatus.OK 
       return results[6] 
      else alert("Geocode was not successful for the following reason: " + status); 
    ) 

我稱其爲Backbone.js的是:

test = @country(origin) 
console.log(test) 

作爲測試我使用的console.log。不過我正在一個:

undefined 

響應,作爲國家功能不返回任何東西。我知道結果[6]中有數據,因爲我可以在那裏做一個conolse.log,並返回。

如何在調用國家函數時返回結果[6]?

回答

1

我不知道API,本身,但它看起來像是異步的,這意味着你不能得到函數返回值。相反,您必須傳入一個繼續函數,該函數在結果可用時處理結果。

country: (origin, handleResult) -> 
    @geocoder = new google.maps.Geocoder 
    @geocoder.geocode(
     'latLng': origin, 
     (results, status) => 
      if status is google.maps.GeocoderStatus.OK 
       handleResult(results[6]) 
      else alert("Geocode was not successful for the following reason: " + status); 
    ) 

要使用這一點,只需手藝,知道做什麼用的結果,並把它傳遞給country功能的函數:

obj.country origin, (result) -> 
    alert 'Got #{result} from Google' 
+0

你需要定義handleResult之前嗎?如果是的話,它應該是什麼? –

+0

從來沒有做過延續功能...... –

+0

@CharlieDavies:我用一個簡單的例子來說明如何使用它。 –

0

在CoffeeScript中在功能上最後一個表達式返回,如在Ruby中。

在這裏,你返回你的console.log

typeof console.log("123") 
> "undefined" 

結果我發現有些人通過把單個@的最後一行,這將只返回this代替,避免了有些尷尬的語法避免這種情況。

+0

嗯它在這個問題以外的作品,但。並在函數本身內部工作。我將如何構建console.log調用? –