【问题标题】:Returning a value from a function CoffeeScript从函数 CoffeeScript 返回一个值
【发布时间】:2012-06-09 16:11:05
【问题描述】:

我有代码:

  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

response,因为 country 函数没有返回任何内容。我知道 results[6] 中有数据,因为我可以在那里做一个 conolse.log 并返回。

如何让 country 函数在调用时返回 result[6]?

【问题讨论】:

    标签: backbone.js coffeescript


    【解决方案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'
    

    【讨论】:

    • 之前需要定义handleResult吗?如果是的话应该是什么?
    • @CharlieDavies:我用一个简短的例子来扩充我的答案,说明如何使用它。
    【解决方案2】:

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

    在这里,您返回 console.log 的结果

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

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

    【讨论】:

    • 嗯,它可以在这个问题之外工作。并在函数本身内部工作。我将如何构建 console.log 调用?
    猜你喜欢
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 2015-12-12
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 2010-09-15
    相关资源
    最近更新 更多