简体   繁体   中英

return value from a jquery get callback function

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.

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 (eg, 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 (eg, take a look at the diff between using -> and => when you compile your coffee)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM