coffeescript is always returning the response object

旧城冷巷雨未停 提交于 2019-12-11 15:43:52

问题


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?


回答1:


$.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.



来源:https://stackoverflow.com/questions/11790685/coffeescript-is-always-returning-the-response-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!