title: Multiple each and ajax requests
body: <p>so this is my setup: I am calling a .each on a number of elements and after a few checks I send an ajax request with some JSON data and on success I apply the server response as an attribute to each element(it is usually an id). After that I push the id to an array.</p>
  
  <p>The problem is that obviously ajax requests are asynchronous and the function that uses the array of element ids fires before all ajax have had time to finish. </p>
  
  <p>I've tried with .when and .then but the callback function keeps getting fired way ahead of the ajax. </p>
  
  <p>Here is how my code looks( I've removed some unnecessary parts):</p>
  
  <pre><code>var order = [];
  
  function sub(selector){
  
  selector.each(function(){
      var out = {
          "some":"random",
          "stuff":"here"
      };
          $.ajax({
              type: "POST" 
              url: "/test/url",
              dataType: 'json',
              contentType: "application/json; charset=utf-8",
              data:JSON.stringify(out),
              success:function(response){
                  $(this).attr("data-response",response);
                  order.push(response);
              }
          })
      })
  }
  
  $("#button").click(function(){
      $.when(sub($(".test"))).then(function() {
          console.log(order);
          //i have to run the sub function twice so the order doesn't return undefined
      });     
  });
  </code></pre>