title: How to call deferred functions sequentially?
body: <p>My code:</p>
  
  <pre><code>&lt;?php
  if(isset($_GET['m'])) {
      $m = $_GET['m'];
      sleep($m);
      print "done, m=$m";
      die;
  }
  ?&gt;
  
  &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" &gt;&lt;/script&gt;
  &lt;script&gt;
  
      function w(s) {
          document.body.innerHTML = document.body.innerHTML+ "&lt;br&gt;" + s
      }
  
      function aaa(def) {
          w("begin aaa");
          $.ajax({
              type: "GET",
              data: {
                  m: 5
              }
          }).done(function(html) {
              w(html);
              def.resolve();
          });
      }
  
  
      function bbb(def) {
          w("begin bbb");
          $.ajax({
              type: "GET",
              data: {
                  m: 1
              }
          }).done(function(html) {
              w(html);
              def.resolve();
          });
      }
  
      $(function() {
  
          $.when(
              $.Deferred(function(d) { aaa(d) }).promise(),
              $.Deferred(function(d) { bbb(d) }).promise()
          ).done(function() {
              w("OK")
          });
      })
  &lt;/script&gt;
  </code></pre>
  
  <p>I'm expecting the second function to wait for the first one to complete, that is, my output should be</p>
  
  <pre><code>begin aaa
     &lt;--pause
  done, m=1
  begin bbb
     &lt;--pause
  done, m=5
  OK
  </code></pre>
  
  <p>Instead I'm getting</p>
  
  <pre><code>begin aaa
  begin bbb
     &lt;--pause
  done, m=1
     &lt;--pause
  done, m=5
  OK
  </code></pre>
  
  <p>I guess I'm misunderstanding something fundamental about how deferreds work - can anyone shed a light?</p>