HungryCoder
HungryCoder

Reputation: 7616

coffeescript is always returning the response object

i've the following codes in coffeescript

getSection = (url) ->
  req = $.getJSON url
  return req.success (data) ->
    data.section

or,

getSection = (url) ->
  req = $.getJSON url
  req.success (data) ->
    data.section

i intended to return data.section for the function getSection. but it is always returning another object (probably the response/ajax object). how can I force to return the values in data.section from this inner function?

thanks in advance?

Upvotes: 0

Views: 1807

Answers (1)

mu is too short
mu is too short

Reputation: 434685

$.getJSON is an AJAX call and A stands for asynchronous so getSection will return before $.getJSON gets its response back from the server. Basically, you can't get getSection to return data.section unless you want to replace $.getJSON with $.ajax and do a synchronous (i.e. non-asynchronous) call; however, synchronous calls are evil and are being deprecated so you shouldn't use them.

The usual solution is to pass a callback to getSection:

getSection = (url, callback) ->
  req = $.getJSON url
  req.success (data) ->
    callback(data.section)

and then you put your logic in callback rather than trying to do something with the getSection return value.

Your getSection is returning req because that's what req.success returns and CoffeeScript functions return their final value.

Upvotes: 3

Related Questions