jquery get回调函数的返回值
-
26-12-2019 - |
题
如果你能帮我修复这个功能,这对我非常有用:
textParseQuery = (txtSnippet) ->
queryUrl = "http://localhost:8083/txtParse/#{txtSnippet}"
console.log queryUrl
callback = (response) =>
parsed = $.parseJSON response
companies = parsed.map (obj) -> new Company(obj.name, obj.addr)
companies
res = $.get queryUrl, {}, callback
console.log res
我想从回调中获取结果,以便 textParseQuery
函数可以返回一个值。
解决方案 2
我发现了 IcedCoffeeScript的 帮助简化异步控制流 await
和 defer
.这就是我试图实现的目标。代码结构是我想象的
# Search for 'keyword' on twitter, then callback 'cb'
# with the results found.
search = (keyword, cb) ->
host = "http://search.twitter.com/"
url = "#{host}/search.json?q=#{keyword}&callback=?"
await $.getJSON url, defer json
cb json.results
其他提示
回调的重点是它是异步的,您的响应来自回调,因此您需要处理回调的其余执行(例如, console.log res
是要在你的回调被调用之前执行,因为它是你的ajax调用的相同同步执行的一部分)。
textParseQuery = (txtSnippet) ->
queryUrl = "http://localhost:8083/txtParse/#{txtSnippet}"
callback = (response) ->
parsed = $.parseJSON response
companies = parsed.map (obj) -> new Company(obj.name, obj.addr)
# proceed from here
console.log companies
$.get queryUrl, {}, callback
附加说明:胖箭头在这里是不必要的,它是用来重新绑定什么 this
引用,但你不是引用 this
在你的回调中。如果你正在学习coffee,大多数编辑器都会有插件/模块来快速将coffee编译为JS,所以使用它来查看给定的coffee语法在JS中编译为什么(例如,看看使用之间的差异 ->
和 =>
当你编译你的咖啡)
不隶属于 StackOverflow