【问题标题】:Method Callback Returning Undefined [CoffeeScript]返回未定义的方法回调 [CoffeeScript]
【发布时间】:2023-03-16 05:54:01
【问题描述】:

我在服务器上使用 HTTP 方法调用一个简单的 google api。看来我正在返回一个 json 对象,但客户端上的回调似乎返回了一个未定义的对象。

我的猜测是,结果没有及时到达回调。有点迷茫。

完整代码在这里:

if Meteor.isClient
    Meteor.startup () ->
        console.log "Client Started."

    Meteor.call("getGeocode", 94582, (error, result) ->
        console.log "GeoCode returned to client, #{result}."
        Session.set("latitude", result))

    Template.results.latitude = () ->
        Session.get("latitude")

    Template.results.longitude = () ->
        "longitude"

if Meteor.isServer
    Meteor.startup () ->
        console.log "Server Started"

    Meteor.methods
        "getGeocode": (zipCode) ->
            result = HTTP.call("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=#{zipCode}&sensor=false")
            console.log "Geocode called, returning #{result}."

【问题讨论】:

    标签: coffeescript meteor


    【解决方案1】:

    您的getGeocode 方法正在返回undefined,因为CoffeeScript 将自动返回函数中最后一条语句的结果,在本例中为console.log

    我不认为result 真的想要你想要的。我建议在isServer 部分的开头包含util,如下所示:

    if Meteor.isServer
      util = Npm.require 'util'
    

    现在您可以致电console.log util.inspect result, {depth: null} 了解它是由什么制成的。我认为您可能真正想要返回的是result.data.results[0]。您的代码可能类似于:

    if Meteor.isClient
      Meteor.startup () ->
        console.log "Client Started."
    
      Meteor.call("getGeocode", 94582, (error, result) ->
        Session.set("latitude", result.geometry.location.lat))
    
      Template.results.latitude = () ->
        Session.get("latitude")
    
      Template.results.longitude = () ->
        "longitude"
    
    if Meteor.isServer
      util = Npm.require 'util'
    
      Meteor.startup () ->
        console.log "Server Started"
    
      Meteor.methods
        "getGeocode": (zipCode) ->
          result = HTTP.call("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=#{zipCode}&sensor=false")
          geoData = result.data.results[0]
          console.log util.inspect geoData, {depth: null}
          geoData
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-18
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      相关资源
      最近更新 更多