Ole Albers
Ole Albers

Reputation: 9285

Filereader.Onload fired too early

I try to read files uploaded by a input type file (multiple). The code is the following:

$(document).ready(function() {
  $('#convert').on('click', function() {
     var files=$('#files')[0].files;
     if (!files) return;
     for (var i=0; i<files.length; i++) {
       var file=files[i];
       fr = new FileReader();
       fr.onload = (function(received) {      
         var note=$(fr.result);
       });
       fr.readAsText(file);
     }
  });
});

Now my problem is: The "onload" - function is called even before the file is loaded. note never has any content. But when I put a breakpoint just before the note - line and wait a while, note gets the content.

So it seems, the onload()-event is called too early. What can I do about that?

(Browser is Chrome)

Upvotes: 0

Views: 204

Answers (2)

Ole Albers
Ole Albers

Reputation: 9285

I replaced fr.result by this.result:

fr.onload = (function() {      
  var note=$(this.result);
});

That did the trick

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

You are making fr a global variable and at the time the onload fires it will be a different object than you expect due to the loop

Try wrapping it in an IIFE to create a closure and making fr a local variable

for (var i = 0; i < files.length; i++) {  
  (function(file) {
    var fr = new FileReader();
    fr.onload = function(received) {
      var note = $(fr.result);// not sure what intent is here
    };
    fr.readAsText(file);
  })(files[i])
}

Upvotes: 0

Related Questions