title: How to break a callback chain in JavaScript?
body: <p>I am uploading multiple files from a browser and need to do so sequentially.</p>
  
  <p>So I chain the next upload commencement from the previous upload completion callback.</p>
  
  <p>It's simple and works just fine.</p>
  
  <p>During the upload I display the progress to the user along with a cancel button.</p>
  
  <p>If the user hits cancel I want to stop the entire callback chain.</p>
  
  <p>How would I do that?  Is there some mechanism in JavaScript to halt my callback chain?</p>
  
  <p>OK here is an example of a callback chain in JavaScript.  The question is, how to break it from a "cancel" button?</p>
  
  <p><a href="https://jsfiddle.net/jq7m9beq/" rel="nofollow">https://jsfiddle.net/jq7m9beq/</a></p>
  
  <pre><code>var filenamesToProcessQueue = ['v.jpg','w.jpg','x.jpg','y.jpg','z.jpg']
  
  function finishedProcessing (filename) {
  console.log('finished processing: ' + filename)
  // processing finished for this file, start again by chaining to the next one
  doProcessFiles()
  }
  
  function waitForEachFile (filename, callback) {
  // wait a couple of seconds and log the filename
  setTimeout(function(){ console.log('Waited 2 seconds for: ' + filename);callback(filename);}, 2000)
  
  }
  
  function doProcessFiles() {
  // get next file to process and remove it from the queue at same time
  filename = filenamesToProcessQueue.pop()
  // if the file is undefined then the queue was empty
  if (typeof filename !== 'undefined') {
  console.log('Process ' + filename)
  waitForEachFile(filename, finishedProcessing)
  }
  }
  
  doProcessFiles()
  </code></pre>