title: Javascript Promises with FileReader()
body: <p>I have the following HTML Code:</p>
  
  <pre><code>&lt;input type='file' multiple&gt;
  </code></pre>
  
  <p>And Here's my JS Code:</p>
  
  <pre><code>var inputFiles = document.getElementsByTagName("input")[0];
  inputFiles.onchange = function(){
      var fr = new FileReader();
      for(var i = 0; i &lt; inputFiles.files.length; i++){
          fr.onload = function(){
              console.log(i) // Prints "0, 3, 2, 1" in case of 4 chosen files
          }
      }
      fr.readAsDataURL(inputFiles.files[i]);
  }
  </code></pre>
  
  <p>So my question is, <strong>how can I make this loop synchronous ?</strong> That is first wait for the file to finish loading then move on to the next file. Someone told me to use JS Promises. But I can't make it to work. Here's what I'm trying:</p>
  
  <pre><code>var inputFiles = document.getElementsByTagName("input")[0];
  inputFiles.onchange = function(){
      for(var i = 0; i &lt; inputFiles.files.length; i++){
          var fr = new FileReader();
          var test = new Promise(function(resolve, reject){
              console.log(i) // Prints 0, 1, 2, 3 just as expected
              resolve(fr.readAsDataURL(inputFiles.files[i]));
          });
          test.then(function(){
              fr.onload = function(){
                  console.log(i); // Prints only 3
              }
          });
      };
  }
  </code></pre>
  
  <p>Thanks in advance...</p>