title: Javascript - too much recursion when executing long chain of promises
body: <p>I have a long sequence of asynchronous functions to be executed sequentially. So I used promises to create promise queue. Unfortunately on Firefox 25.0.1 on Linux I'm getting <code>too much recursion</code> JavaScript error. It works fine on the same Firefox version on Mac, it works in chrome as well. But I need it working everywhere, including Linux. Can you propose better implementation of <code>executePromiseQueueSync</code> function?</p>
  
  <pre><code>//-----------------------------------------------------------------------------------------
  
  function executePromiseQueueSync(queue){
       var seed = $.Deferred(); 
       var acc = seed;
  
       for (var i = 0; i &lt; queue.length; ++i )
       {
           var promise = queue[i];
           acc = acc.then(promise.funct.apply(null, promise.argmnt));
       }
  
      seed.resolve();
      return acc;
  }
  
  //-----------------------------------------------------------------------------------------
  
  function someTask(){
      var dfd = new jQuery.Deferred();
      dfd.notify();
      dfd.resolve();
      return dfd.promise();
  }
  
  //-----------------------------------------------------------------------------------------
  
  $(function(){
      var promisesQueue = []
  
      for(var i = 0; i &lt; 200; ++i){
          promisesQueue.push({funct:someTask, argmnt:[]});
      }
  
      executePromiseQueueSync(promisesQueue).then(function(){alert('done!');});
  });
  
  //-----------------------------------------------------------------------------------------
  </code></pre>
  
  <p>JSFiddle example:  <a href="http://jsfiddle.net/C2YN4/4/" rel="nofollow">http://jsfiddle.net/C2YN4/4/</a></p>
  
  <p><strong>What I have so far</strong> (and I'm very open to other propositions and corrections):</p>
  
  <pre><code>function executePromiseQueueSync(queue){
  
      if (queue.length &gt; TRESHOLD){
          var i,j;
          var shortQueue = []
          for (i=0,j=queue.length; i&lt;j; i+=TRESHOLD) {
            temparray = queue.slice(i, i+TRESHOLD);
            shortQueue.push({funct:executePromiseQueueSync, argmnt:[temparray]});
          }
          return executePromiseQueueSync(shortQueue);
      }
  
      var seed = $.Deferred(); 
      var acc = seed;
  
      for (var i = 0; i &lt; queue.length; ++i )
      {
           var promise = queue[i];
           acc = acc.then(promise.funct.apply(null, promise.argmnt));
      }
  
      seed.resolve();
      return acc;
  }
  </code></pre>
  
  <p>So the basic idea is to make a promise tree instead of promise chain. This way we don't go so much deep into stack.</p>
  
  <p>example: <a href="http://jsfiddle.net/fMBJK/1/" rel="nofollow">http://jsfiddle.net/fMBJK/1/</a></p>