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?
$.getJSONis an AJAX call and A stands for asynchronous sogetSectionwill return before$.getJSONgets its response back from the server. Basically, you can’t getgetSectionto returndata.sectionunless you want to replace$.getJSONwith$.ajaxand 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:and then you put your logic in
callbackrather than trying to do something with thegetSectionreturn value.Your
getSectionis returningreqbecause that’s whatreq.successreturns and CoffeeScript functions return their final value.