callbackcoffeescripticed-coffeescript

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.


Solution

  • 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