title: AngularJS $q. Deferred queue
body: <p>I have array (f.e. it is queue of files):</p>
  
  <pre><code>[{deferred: fileDef, data: file}, {...}, ...]
  </code></pre>
  
  <p>Each <em>fileDef</em> and <em>file</em> send to upload function which return <em>fileDef.promise</em> and call <em>fileDef.resolve</em> or <em>fileDef.reject</em> after uploading.</p>
  
  <p>I want upload files in order: next file upload after previous file is loaded.</p>
  
  <p>Now I use
  </p>
  
  <pre class="lang-js prettyprint-override"><code>var queue = [];
  var uploading = false;
  
  //file input callback call each time the user selects files
  function addAndUpload (file) {
  
    queue.push({deferred: $q.defer(), data: file});
  
    if (!uploading) recurceQueue();
  
    function recurceQueue () {
      if (queue.length) {
        uploading = true;
        var fileObj = queue.shift();
        upload(fileObj.deferred, fileObj.data);
  
        fileObj.deferred.promise.finally(function () {
          uploading = false;
          recurceQueue();
        })
      }
    }
  }
  </code></pre>
  
  <p>But it seems bad. How to write better?</p>