title: jQuery Deferred and Promise for sequential execution of synchronous and asynchronous functions
body: <p>If I want to have synchronous and asynchronous functions execute in a particular order I could use jQuery promise but it doesn't seem to work the way I'd expect it to work.</p>
  
  <p>Functions a,b and c should execute in that order when in a the <code>deferred.resolve()</code> is called I'd expect function b to be executed but all functions are executed immediately no matter if the resolve is called.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>function a(){
    var deferred = $.Deferred();
    setTimeout(function(){
      console.log("status in a:",deferred.state());
      //this should trigger calling a or not?
      deferred.resolve("from a");
    },200);
    console.log("a");
    return deferred.promise();
  };
  function b(){
    var deferred = $.Deferred();
    setTimeout(function(){
      console.log("status in b:",deferred.state());
      deferred.resolve("from b");
    },200);
    console.log("b");
    return deferred.promise();
  }
  //synchronous function
  function c(){
    var deferred = $.Deferred();
    console.log("c");
    console.log("status in c:",deferred.state());
    deferred.resolve("from c");
    return deferred.promise();
  }
  function test(){
    fn=[a,b,c],i=-1,
    len = fn.length,d,
    d = jQuery.Deferred(),
    p=d.promise();
    while(++i&lt;len){
      p=p.then(fn[i]);
    }
    p.then(function(){
      console.log("done");
    },
    function(){
      console.log("Failed");
    });
    d.resolve();
    //instead of the loop doing the following has the same output
    //p.then(a).then(b).then(c);
    //d.resolve();
  }
  test();
  </code></pre>
  
  <p>Output is:</p>
  
  <pre><code>a
  b
  status in c: pending
  c
  done
  status in a: pending
  status in b: pending
  </code></pre>
  
  <p>Expected output:</p>
  
  <pre><code>a
  status in a: pending
  b
  status in b: pending
  c
  status in c: pending
  done
  </code></pre>
  
  <p>Tried a some combinations of the following modifications:</p>
  
  <pre><code>  d = jQuery.Deferred();
    setTimeout(function(){d.resolve();},100);
    var p=d.promise();
    while(++i&lt;len){
      p.then(fn[i]);
    }
  </code></pre>
  
  <p>But all with same unexpected results, b gets called before deferred of a is resolved, c is called before deferred of b is resolved.</p>