title: How do you know when an indefinitely long promise chain has completely finished?
body: <p>I was trying to use promises to force serialization of a series of Ajax calls.  These Ajax calls are made one for each time a user presses a button.  I can successfully serialize the operations like this:</p>
  
  <pre><code>// sample async function
  // real-world this is an Ajax call
  function delay(val) {
      log("start: ", val);
      return new Promise(function(resolve)  {
          setTimeout(function() {
              log("end: ", val); 
              resolve();
          }, 500);
      });
  }
  
  // initialize p to a resolved promise
  var p = Promise.resolve();
  var v = 1;
  
  // each click adds a new task to 
  // the serially executed queue
  $("#run").click(function() {
      // How to detect here that there are no other unresolved .then()
      // handlers on the current value of p?
      p = p.then(function() {
          return delay(v++);
      });
  });
  </code></pre>
  
  <p>Working demo: <a href="http://jsfiddle.net/jfriend00/4hfyahs3/" rel="noreferrer">http://jsfiddle.net/jfriend00/4hfyahs3/</a></p>
  
  <p>But, this builds a potentially never ending promise chain since the variable <code>p</code> that stores the last promise is never cleared.  Every new operation just chains onto the prior promise.  So, I was thinking that for good memory management, I should be able to detect when there are no more <code>.then()</code> handlers left to run on the current value of <code>p</code> and I can then reset the value of <code>p</code>, making sure that any objects that the previous chain of promise handlers might have held in closures will be eligible for garbage collection.</p>
  
  <p>So, I was wondering how I would know in a given <code>.then()</code> handler that there are no more <code>.then()</code> handlers to be called in this chain and thus, I can just do <code>p = Promise.resolve()</code> to reset <code>p</code> and release the previous promise chain rather than just continually adding onto it.</p>