FileReader API: how to read files synchronously

I am trying to read a file that is selected using an input type file in an html page. I implemented a function to read the file, and the contents of the file can be read. But the actual problem is that reading the contents of the file is asynchronous , which allows other script functions to be performed. I save the contents of a file read in an array.

When moving to other functions, the array is empty. When a delay is introduced, the array has content. Can someone help me solve this problem without introducing a delay?

My code to read the file

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.

+4
source share
1 answer

I think you need to do what you always need with an asynchronous call (e.g. Ajax): move the code that you want to run later to the callback that starts 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 } 
+5
source

Source: https://habr.com/ru/post/1390821/


All Articles