return value from a jquery get callback function
-
26-12-2019 - |
Question
It would be very useful to me if you could help me fix this function:
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
I would like to fetch the results from the callback so that the textParseQuery
function could return a value.
Solution 2
I have discovered IcedCoffeeScript helps streamline the asynchronous control flow with await
and defer
. This is what I have tried to achieve. The code structure is how I pictured it
# 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
OTHER TIPS
The point of a callback is it's asynchronous, your response comes in the callback, so you need to handle the rest of the execution from the callback (e.g., the console.log res
is going to execute before your callback is called, since it's part of the same synchronous execution of your ajax call).
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
Additional note: the fat arrow is unnecessary here, it's used to rebind what this
refers to, but you aren't referencing this
at all in your callback. If you're learning coffee, most editors will have plugin/modules to quickly compile coffee to JS, so use that to see what a given coffee syntax compiles to in JS (e.g., take a look at the diff between using ->
and =>
when you compile your coffee)