
Question:
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?
Answer1:<a href="http://api.jquery.com/jQuery.getJSON/" rel="nofollow">$.getJSON
</a> is an AJAX call and <strong>A</strong> stands for <strong>asynchronous</strong> 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 <a href="http://api.jquery.com/jQuery.ajax/" rel="nofollow">$.ajax
</a> 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 <a href="http://api.jquery.com/jQuery.ajax/#jqXHR" rel="nofollow">req.success
</a> returns and CoffeeScript functions return their final value.