0

Consider this contrived example

reqs = for url in urls
  $.ajax
    url: url
    successs: (resp) =>
      # here, url is always the last url, 
      # apparently because closure doesn't copy the captured locals
      console.log "response for url: #{url}"

What is the best way to determine which url belong to which request in the success case?

Later, there is a call

$.when(reqs...).then (resps...) =>
  console.log(resps)

Still, now way to know, because the order of resps might differ from reqs' order, right?

evfwcqcg
  • 15,755
  • 15
  • 55
  • 72
  • Send a unique randomly generated 'key' along with the request, use that for the key in your resp array. Have the back end process send that key back with the response so you can store the response data into the appropriate resp key/value pair. – Drew Mar 09 '15 at 13:35
  • @Drew, that might be a reasonable option if you have an access to back-end code but what if you don't? I think there should be a way to do this on the front-end side only, but I'm running out of ideas. – evfwcqcg Mar 09 '15 at 13:41
  • 1
    I don't know coffeescript, but in plain JS you could make `url` be the correct one within the `success` handler by wrapping the call in an immediately invoked function and passing the current url in - eg in [this answer](http://stackoverflow.com/a/19324832/791010) - is that sort of thing possible in coffeescript? – James Thorpe Mar 09 '15 at 13:43
  • Write it up as a coffeescript version of an IIFE in an answer then - personally I haven't got a clue what it would look like :) – James Thorpe Mar 09 '15 at 13:59
  • Okay, that might look a bit weird due to brackets but still `success: ((url) -> ((resp) -> console.log(url)))(url)` – evfwcqcg Mar 09 '15 at 14:01

1 Answers1

0

Thanks to the comment by James, the solution is

reqs = for url in urls
  success_fn = (url) =>
    (resp) =>
      console.log "response for url: #{url}"
      console.log resp
  $.ajax
    url: url
    successs: success_fn(url)
evfwcqcg
  • 15,755
  • 15
  • 55
  • 72