FileReader API:如何同步读取文件

AmG*_*tes 5 javascript file-io asynchronous synchronized

我正在尝试读取使用html页面上的输入类型文件选择的文件.我已经实现了读取文件的功能,并且可以读取文件内容.但实际问题是文件内容的读取是异步完成的,这允许脚本的其他功能执行.我正在将数据的内容存储在数组中.

移动到其他函数时,数组为空.当引入延迟时,阵列具有内容.任何人都可以帮我解决这个问题,而不会引起延迟吗?

我的阅读文件的代码是

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]);
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Thi*_*ilo 5

我认为您必须使用异步调用(例如Ajax)来执行您必须执行的操作:将稍后需要运行的代码移动到读取文件时执行的回调.

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

} 
Run Code Online (Sandbox Code Playgroud)