title: javascript set promise callback after the promise had finished execution
body: <p>In the following snippet I am trying to set the <code>Promise</code> callback <em>after</em> the promise is supposed to be finished.</p>
  
  <p>For some reason, it seems to "remember" to execute the callback after I expect the future to finish it's execution.</p>
  
  <p>Why is it so?</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> 
   'use strict';
   var promiseCount = 0;
   
   function testPromise() {
    var thisPromiseCount = ++promiseCount;
  
    var log = document.getElementById('log');
    log.insertAdjacentHTML('beforeend', thisPromiseCount +
     ') Started (&lt;small&gt;Sync code started&lt;/small&gt;)&lt;br/&gt;');
  
    // We make a new promise: we promise the string 'result' (after waiting 3s)
    var p1 = new Promise(
     // The resolver function is called with the ability to resolve or
     // reject the promise
     function(resolve, reject) {
     
      log.insertAdjacentHTML('beforeend', thisPromiseCount +
       ')  the promise is started(&lt;small&gt;Async code started&lt;/small&gt;)&lt;br/&gt;');
      
      resolve(thisPromiseCount);
  
      log.insertAdjacentHTML('beforeend',promiseCount+ ') the promise is supposed to finish&lt;br/&gt;');
       
     });
  
     window.setTimeout(
      function() {
         log.insertAdjacentHTML('beforeend', thisPromiseCount +
          ') we set the callback much after the proise has finished&lt;br/&gt;');
       p1.then(
        // Log the fulfillment value
        function(val) {
         log.insertAdjacentHTML('beforeend', val +
          ') and still the promise executes the callback!(&lt;small&gt;Async code terminated&lt;/small&gt;)&lt;br/&gt;');
        })
       .catch(
        // Log the rejection reason
        function(reason) {
         console.log('Handle rejected promise ('+reason+') here.');
        });
      }, 5000);
  
    log.insertAdjacentHTML('beforeend', thisPromiseCount +
     ') Sync code terminated&lt;br/&gt;');
   }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button type="button" onclick='testPromise()' /&gt;test&lt;/button&gt;
  &lt;div id="log"&gt;&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>