4

I want to execute some $.ajax() requisitions in a certain order, so I tried to use $.when like this:(just for testing)

$.when.apply(null,[ajaxRequisition1(),ajaxRequisition2()] ).then(function () {
    console.log("Completed all requests.");
    });

But it shoots the message on the console before the requisitions are done. Any suggestions?

Thanks

EDIT

Here are one of my requisitions. I'll post one, but the others are very similar, changing only some parameters.

code:

function ajaxRequisition1(){ 
$.ajax({
       type:'GET',
       crossDomain:true,
       url:'http://www.myurl.com.br/api/my_php.php?callbackplat=?',
       dataType:'jsonp',
       data: {currency: $('#cur').val()},
       beforeSend: function(){
           $('#loading').css("display","block");
           $('table[name=tb_latam]').css("opacity","0.01");

       }    

    }).done(function(data){
            console.log(data);
            //HERE I BUILD A TABLE USING THE DATA RECEIVED.

           $('#loading').css("display","none");
           $('table[name=tb_latam]').css("opacity","1");


           $('#tb_latam').append('<tr> <td data-nome="A-ACTIVE" class="column_st">'+'Active'+
                                '</td><td class="c_qtdA column_qtd">'+data.lat_qtdA+
                                '</td><td id="a2"class="a">'+data.lat_active+
                                '</td><td>'+data.lat_p_active+'</td></tr>');


           $('#tb_latam').append('<tr> <td data-nome="I-INACTIVE" class="column_st">'+'Inactive'+
                                '</td><td class="c_qtdI column_qtd">'+data.lat_qtdI+
                                '</td><td class="i">'+data.lat_inactive+
                                '</td><td>'+data.lat_p_inactive+'</td></tr>');

           $('#tb_latam').append('<tr> <td data-nome="R-REPLACED" class="column_st">'+'Replaced'+
                                '</td><td class="c_qtdR column_qtd">'+data.lat_qtdR+
                                '</td><td  class="r">'+data.lat_replaced+
                                '</td><td>'+' - '+'</td></tr>');

    })
     .fail(function(data, textStatus, errorThrown){
        alert("ERROR!.");
        console.log(data);
        console.log(textStatus);
        console.log(errorThrown);
    });
   return false; 
}
Lioo
  • 375
  • 6
  • 20

2 Answers2

4

jQuery $.when() accepts deferred objects. While your ajaxRequisition returns a non deferred, $.when() will then return a resolved promise.

Try to change your code,

function ajaxRequisition1 () {
    return $.ajax({
        ...
    });
}

function ajaxRequisition2 () {
    return $.ajax({
        ...
    });
}

$.when.apply(null, [ajaxRequisition1(),ajaxRequisition2()]).done(function () {
    console.log("Completed all requests.");
});
choz
  • 17,242
  • 4
  • 53
  • 73
2

I believe you need to use .done(...).

Check this to learn the differences.

edit

As per the docs of jquery, if you pass NOT-a-promise to the .when(...) method, the .then(...) will get called automatically and treat the arguments you passed to .when(...) as already resolved promises, and also pass them to the .then(...)

So, the array you're passing have to be promises so that the .when(...) gets called at the correct time.

If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.

Check docs.

edit 2

I thought your ajaxRequisitions methods were already working. Here's the example from the docs to the .when(...) function

$.when( $.ajax( "test.aspx" ) ).then(function(
        data, textStatus, jqXHR ) {
    alert( jqXHR.status ); // Alerts 200
});

You need to update it so you can add the .apply(...), and have your ajaxRequisition... Methods return the Ajax call you need in each one.

Community
  • 1
  • 1
onzinsky
  • 541
  • 1
  • 6
  • 21
  • Hi, I changed to `.done`, but it didn't changed anything, the console message keeps coming before the requisitions finish. – Lioo Jun 03 '16 at 03:05
  • Ok I see now maybe your problem is another. I'm updating answer – onzinsky Jun 03 '16 at 03:09
  • Uhn, okay, but the ´$.ajax()´ requisitions doesn't already return as Promisses? If not, how can I make they do? Can you give me a working example? – Lioo Jun 03 '16 at 03:23
  • Can't, don't have a computer at hand, but you're not doing any Ajax request here. I'm posting an example from the docs I linked – onzinsky Jun 03 '16 at 03:27
  • If you could post your ajaxRequisition methods that would help to find your problem – onzinsky Jun 03 '16 at 03:42