Search code examples
jqueryjqxhr.when

Can you have embedded when.applys() in jQuery?


I'm trying to use 2 $.when.apply()'s with $.ajax and $.getJSON. I'm trying to embed one inside the other, but it doesn't seem to be working. Here's the outline:

var jxhr = [];
var kxhr = [];

$.when($.getJSON('stuff.js', function(cart){
    //Grab Stuff
})).then(function(){
       for(i<stuff)
       {
           jxhr.push($.getJSON(array[stuff])
       }

       $.when.apply($, jxhr).done(function()
       {
           for(i<array2)
           {
               kxhr.push($.getJSON(array2[morestuff]))

           }
           $.when.apply($, kxhr).done(function())
           {
               //Finish up here.
               //Not running.
           }
       });
}

There are some syntax errors from me pulling bits of code out, but the structure should be there. The problem is that the second $.when.apply() doesn't run. Is this a restriction? Is there a better way to structure this code that doesn't use the embedded whens?


Solution

  • Here's a more vertical chaining of promises approach. Since $.getJSON itself returns promise, no need to wrap first call in $.when. Note that the 2 then's have to resolve in sequence before the final done is called

    $.getJSON(url, function(cart) {
       $('body').append('<p>First getJSON call made</p>');
    }).then(function(){
      var jxhr = [];
       $('body').append('<p>Start first loop then</p>')
      for (var i = 0; i < 5; i++) {
        jxhr.push(getSomeData('Loop 1'))
      }      
      return  $.when.apply($, jxhr)
    }).then(function(){
       var kxhr = [];
      $('body').append('<p>Start second loop then</p>')
       for (var i = 0; i < 5; i++) {
          kxhr.push(getSomeData('Loop2'))
        }
       return $.when.apply(null, kxhr)
    }).done(function(){
       $('body').append('<p>DONE!</p>');
    
    });
    
    
    function getSomeData(loop) {
      return  $.getJSON(url, function(res) {
          $('body').append('<p>'+loop+' getJSON call made</p>');
      })
    }
    

    DEMO

    UPDATED DEMO (slightly more real world data processing with nested array data output)