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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With