title: FileReader and Callbacks
body: <p>I am struggling trying to re-work the idea/code found <a href="https://stackoverflow.com/questions/18299806/how-to-check-file-mime-type-with-javascript-before-upload">here</a> (basic premise being working out a file type by simply looking at the first few bytes of data).</p>
  
  <p>Ive got the bare bones of doing what i want - see <a href="http://jsfiddle.net/of67rs74/" rel="nofollow noreferrer">JSFIDDLE</a>.</p>
  
  <p>Heres my code:</p>
  
  <pre><code>function readTheFiles(file){
  
              var fileReader = new FileReader();
              fileReader.onloadend = function(e) {
              var fileHeader = new Uint8Array(e.target.result).subarray(0, 4);
              var header = "";
              for (var q = 0; q &lt; fileHeader.length; q++) {
              header += fileHeader[q].toString(16);
              }
              alert(header);
              return header;              
              };
  fileReader.readAsArrayBuffer(file);
  
  } 
  
  
  $("#input-id").on('change', function(event) {
          var files = event.target.files;
          var i = 0;
          for (var i = 0, file; file = files[i]; i++) {
  
           var headString = readTheFiles(file);
         alert(headString);
  
          }       
      });   
  </code></pre>
  
  <p>From what ive read (<a href="https://stackoverflow.com/questions/11829537/html5-filereader-how-to-return-result">example 1</a>, <a href="https://stackoverflow.com/questions/21718266/javascript-filereader-and-a-possible-return-or-closure-issue">example 2</a>) i am sure that the issue lies with calling a callback in the <strong>readTheFiles</strong> function - presumably the code is calling the alert(headString) line before the files have been loaded (hence why the alert within the <strong>readTheFiles</strong> function gives the expected result).</p>
  
  <p>Im keen to understand the principal, rather than just get a solution, so any pointers/advice/assistance would be gratefully received.</p>
  
  <p>Many Thanks</p>