title: Running multiple deferred groups sequentially
body: <p>So I have been messing around with $.Deferred() and can't quite get it to work the way I want.</p>
  
  <p>The idea is to run a group of 10 items, wait for it to finish, run the next group, wait for it to finish, etc.</p>
  
  <p>The code below produces this output</p>
  
  <pre><code>(3)Item Complete
  (30)Item Finished
  </code></pre>
  
  <p>.</p>
  
  <pre><code>indexedDB.deleteDatabase("_pouch_test")
  db = new PouchDB('test');
  
  function item(limit){
      var d = $.Deferred();
      var promises = []
      var url = ""//url that will respond with up to limit responces
      $.getJSON(url,function(data){
          $.each(data.items,function(i, item){
                  promises.push( db.post({item:"test"}).then(console.log("Item Finished ")) )
          })
      }).fail(function( jqxhr, textStatus, error ) {
          var err = textStatus + ", " + error;
          console.log( "Request Failed: " + err );
      });
      return $.when.apply($,promises).promise()
  }
  
  function group(times){
      var d = $.Deferred().resolve()
      for( var i=0; i&lt;times; i++){
          d.then( item(10).then( function(){console.log("Group Complete")} ) )
      }
      return d.promise()
  }
  
  function init(){
      group(3).then("All Complete")
  }
  </code></pre>
  
  <p>What I am expecting is output like</p>
  
  <pre><code>(10)Item Finished
  Group Complete
  (10)Item Finished
  Group Complete
  (10)Item Finished
  Group Complete
  All Complete
  </code></pre>
  
  <p>If anyone can point me in the right direction, that would be great. I'm thinking i'm doing the $.when incorrectly, but don't know another way.</p>
  
  <p>Thanks Again.</p>
  
  <p>--edit: After looking back over, I believe the promises array is empty when it is handed to $.when, still now sure how to fix it though.</p>
  
  <p>--edit2: <a href="http://pastebin.com/raw/cAU7Fj0g" rel="nofollow">updated code</a> produces output below, but "All complete" is being displayed first? It should be last.</p>
  
  <pre><code>All Complete
  (10)Item finished
  Group Finished
  (10)Item finished
  Group Finished
  (10)Item finished
  Group Finished
  </code></pre>
  
  <p>--edit3: <a href="http://pastebin.com/raw/G0y0FRLF" rel="nofollow">So I solved it</a>. I had to assign the updated deferred to the variable as well as wrap the inside of the then in a function. I'm sure the code could be more efficient, but it's a great starting point.</p>