1

My script needs to handle several ajax requests. Here is a simplified version:

function request(variable){
    $.ajax({
        // call config
    }).done(function(data){
        // treatment of returned data
        // returning TRUE (ok) or FALSE (errors)
    }).fail(function(e){
        // generating error message
    });
}

I need to make several calls:

request(variableA);
request(variableB);
request(variableC);

Requests are performed simultaneously and work well, but I don't know when the process is finished. And I can't display returned values.

Some discussions suggest to use when().

  $.when(request(variableA), request(variableB), request(variableC))
   .done(function(resultA, resultB, resultC) { 
         alert("Finished!");
         //results available
    });

Using this code, alert seems to be performed at the very beginning of the process instead of waiting for completion...

What would be my best option ?

Yako
  • 3,405
  • 9
  • 41
  • 71

2 Answers2

4

Change request to return the promise

function request(variable){
    return $.ajax({
        // call config
    }).done(function(data){
        // treatment of returned data
        // returning TRUE (ok) or FALSE (errors)
    }).fail(function(e){
        // generating error message
    });
}
Musa
  • 96,336
  • 17
  • 118
  • 137
2

Those request() calls would immediately return anyways, because they are ASYNCHRONOUS (hence the A in AJAX). To chain the requests together and only execution something when they're all done, you'd have to have the individual ajax call's success handlers increment a counter and then only call the "go ahead" code when the counter reaches a certain point. e.g.

var alert_counter = 0;
function request('blahblah', alert_when_reached) {
$.ajax({
     success: function() { 
        alert_counter++;
        if(alert_when_reached >= alert_counter) {
           proceed_onwards();
        }
     });

not that this will work as is, but should give you the idea. If you need to call 3 paralle requests, you pass in 3 to each of those requests, and when the 3rd result finally comes in, that particular instance of the success handler will invoke whatever function lets your code proceed onwards.

Some minor enhancements would be to define a closure for the success handler and pass it into the request() function, so you don't have a hard-coded "proceed" function call, but that's beyond the scope of this answer.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Thanks for your anwser. Indeed, I was turning towards a counter solution, as I could not understand the deferred object, and your solution is effective in this view. However, I prefer to use Musa's option; it is lighter and more optimal with jQuery. – Yako Feb 16 '13 at 09:40