title: JavaScript Promise then() ordering
body: <p>I'm still learning JavaScript <code>Promise</code>s, and I came across a behavior I don't understand.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var o = $("#output");
  var w = function(s) {
      o.append(s + "&lt;br /&gt;");
  }
  
  var p = Promise.resolve().then(function() {
      w(0);
  }).then(function() {
      w(1);
  });
  
  p.then(function() {
      w(2);
      return new Promise(function(r) {
          w(3);
          r();
      }).then(function() {
          w(4);
      });
  }).then(function() {
      w(5);
  });
  
  p.then(function() {
      w(6);
  });</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;div id="output"&gt;&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>I would expect these statements to run in order--that is, the that output would be</p>
  
  <pre><code>0
  1
  2
  3
  4
  5
  6
  </code></pre>
  
  <p>Instead, the output is </p>
  
  <pre><code>0
  1
  2
  3
  6
  4
  5
  </code></pre>
  
  <p>Even removing the inner <code>Promise</code> gives, what seems to me to be, contradicting results.  <code>1</code> is output before <code>2</code>, but <code>6</code> is output before <code>5</code>.</p>
  
  <p>Can someone explain this to me?</p>
  
  <p>Something I have noticed is that reassigning <code>p</code> each time gives us the order I would expect.</p>