I am trying to get a total from the return of multiple ajax requests, I use sync right now to make it work, since I think that would be a much better solution.
Here is my Coffee
get_total = (trend, duration) ->
total = 0
for keyword in trend.search_terms
url = "http://otter.topsy.com/search.json?q=#{keyword}&window=#{duration}"
$.ajax
url: url
async: false
success: (data) ->
total += data.response.total
total
Which compiles nicely to
get_total = function(trend, duration) {
var keyword, total, url, _i, _len, _ref;
total = 0;
_ref = trend.search_terms;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
keyword = _ref[_i];
url = "http://otter.topsy.com/search.json?q=" + keyword + "&window=" + duration;
$.ajax({
url: url,
async: false,
success: function(data) {
return total += data.response.total;
}
});
}
return total;
};
Is there a way to have the total work without using synchronous js.
I have been experimenting with the $.when().then() but it is causing issues when the size of the requests is dynamic.
I don’t know CoffeeScript, so here is a pure jQuery solution:
You cannot return a value from
get_totalwithout making synchronous calls. What you can do is call a callback, once all the requests have finished.This example makes use of jQuery’s
Deferredobjects [docs]:Usage:
If you need
get_totalto return the value, then you have to make synchronous calls. In general this is a bad idea, especially when you are making multiple requests. It will freeze the browser’s UI. Better you restructure your code to work with callbacks.Update: I just read the last sentence of your question. You you can pass a dynamic number of arguments to a function using
.apply()[MDN].Update2: Of course if you have control over the service, you should make it accept multiple keywords to avoid multiple Ajax requests.