Yako
Yako

Reputation: 3484

How to handle several ajax requests?

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 ?

Upvotes: 1

Views: 144

Answers (2)

Musa
Musa

Reputation: 97672

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
    });
}

Upvotes: 4

Marc B
Marc B

Reputation: 360672

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.

Upvotes: 2

Related Questions