coffeescript总是返回响应对象 [英] coffeescript is always returning the response object
问题描述
我在coffeescript中有以下代码
getSection =(url) - >
req = $ .getJSON url
return req.success(data) - >
data.section
或
getSection =(url) - >
req = $ .getJSON url
req.success(data) - >
data.section
我打算返回 data.section
用于函数 getSection
。但它总是返回另一个对象(可能是响应/ ajax对象)。如何提前感谢?
< >解决方案
$。getJSON
是AJAX调用, A 代表异步,因此 getSection
将在 $。getJSON
从服务器获取其响应。基本上,你不能得到 getSection
返回 data.section
,除非你要替换 $ .getJSON
与 $。ajax
并执行同步(即非异步)调用;
通常的解决方案是传递一个回调到 getSection
:
getSection =(url,callback) - >
req = $ .getJSON url
req.success(data) - >
callback(data.section)
然后将你的逻辑放在 callback
,而不是尝试使用 getSection
返回值做某事。
您的 getSection
正在返回 req
,因为这是 req.success
返回,CoffeeScript函数返回其最终值。
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?
$.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.
这篇关于coffeescript总是返回响应对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!