ppedrazzi
ppedrazzi

Reputation: 787

Method Callback Returning Undefined [CoffeeScript]

I am calling a simple google api using an HTTP method on the server. It appears I am getting a json object back, yet the callback on the client seems to return an undefined object.

My guess is somehow the result isn't making it to the callback in time. A bit confused.

Full code here:

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}."

Upvotes: 0

Views: 569

Answers (1)

David Weldon
David Weldon

Reputation: 64312

Your getGeocode method is returning undefined because CoffeeScript will automatically return the result last statement in the function, which in this case is a console.log.

I don't think result is really want you want though. I recommend including util at the start of your isServer section like so:

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

Now you can call console.log util.inspect result, {depth: null} to see what it's made of. I think what you may actually want to return is result.data.results[0]. Your code could look something like:

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

Upvotes: 1

Related Questions