从函数CoffeeScript返回一个值

时间:2012-06-09 16:11:05

标签: backbone.js 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]?

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分:0)

在CoffeeScript中,返回函数中的最后一个表达式,如Ruby。

在这里,您返回console.log

的结果
typeof console.log("123")
> "undefined"

我注意到有些人通过将一个@作为最后一行来避免这种情况,而这只会返回this而避免一些笨拙的语法。