jQuery each + FileReader not returning correct values

128 views Asked by At

I'm trying to read 2 CSV files which contains rows of numbers each.

<input type="file" id="file[0]" name="file[0]">
<input type="file" id="file[1]" name="file[1]">

File 1 content:

111
222

File 2 content:

333
444

After reading the contents, I push the numbers to new array (csv_arr) and count the occurrences (csv_cnt).

var csv_arr = new Array();
var csv_cnt = 0;

$("[id^=file]").each(function(index) {
    file = $(this)[0].files[0];

    if (file) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var csv_val = e.target.result.split("\r\n");

            for (var i = 0; i < csv_val.length; i++) {
                csv_arr.push( csv_val[i] );
                csv_cnt++;
            }
        };
        reader.readAsText(file);
    }
});

console.log(csv_arr);
console.log(csv_arr.length);
console.log(csv_cnt);

The result of the console.log are:

['111','222','333','444']
0
0

As you can see from the result, the array looks ok, but then the array length and count are 0! I'm stuck and not sure what is really wrong. Any idea?

1

There are 1 answers

1
Roko C. Buljan On

Your code works beside you forgot that filereader is asyncronous.
That means that your console.logs will trigger while the onload is still loading data.

And no. your Array, (at least with the exact code you posted) cannot result in what you said - Otherwise you'd get the 4 and 4 since the Array has values. That means that you're getting this instead:

[]
0
0

Pass the console.logs into the onload function and you'll get this:

["111", "222"]
2
2
["111", "222", "333", "444"]
4
4