FileReader API: how to read files synchronously

2019-06-21 05:27发布

问题:

I am trying to read a file which is selected using an input type file on the html page. I have implemented the function to read the file and the file content is able to be read. But the actual problem is that the reading of the content of the file is being done asynchronously which allows the other functions of the script to execute. I am storing the content of the file read in an array.

While moving to the other functions the array is empty. When delay is introduced then the array has the content. Can anybody help me out in solving this problem without introducing a delay?

My code for reading the file is

var getBinaryDataReader = new FileReader();
getBinaryDataReader.onload = (function(theFile) {
return function(frEvnt)
{
  file[fileCnt]=frEvnt.target.result;
}
})(document.forms[formPos].elements[j].files[0]);

getBinaryDataReader.readAsBinaryString(document.forms[formPos].elements[j].files[0]);

Thanks in advance.

回答1:

I think you have to do what you always have to with asynchronous call (like Ajax, too): Move the code that needs to run later into the callback that gets executed when the file has been read.

getBinaryDataReader.onload = function(theFile) {
   // theFile.target.result has your binary
   // you can move it into the array
   // (I think you are already doing this properly)
   // but then ...
   nowCallTheOtherCodeThatNeedsToRunLater();

   // or if you want to wait until all elements
   // in the array are downloaded now
   if (myArrayIsFullNow()){
      callTheCodeThatNeedsTheFullArray();
   }
   // else: do nothing, the final file to finish downloading
   // will trigger the code

}