For some reason when elements are pushed to an array in the FileReader.onload event function, the elements of that array are later inaccessible. Consider the following code:
scope.targets = [];
for(var i = 0; i < files.length; i++){
var reader = new FileReader();
reader.readAsDataURL(files[i]);
reader.onload = function(e){
scope.targets.push(e.target.result);
};
}
console.log(scope.targets);
console.log(scope.targets[0]);
This is the result of the console.log() outputs in Google Chrome Browser. As you can see scope.targets reveals that there's an element of type string. However, scope.targets[0] is undefined. Why is this happening? Is there another way to access the element?
**************************UPDATE*************************************
Here's a solution. Thank You Ashwin Balamohan and nnnnn for your answers, it led me to find a solution. I found what I was looking for here How to implement Progress Bar and Callbacks with async nature of the FileReader
The Solution is:
scope.targets = [];
for(var i = 0; i < files.length; i++){
var reader = new FileReader();
reader.readAsDataURL(files[i]);
reader.onload = function(e){
scope.targets.push(e.target.result);
if(i == files.length){
callback();
}
};
}
var callback = function(){
console.log("scope.targets:");
console.log(scope.targets);
console.log("scope.targets[0]:");
console.log(scope.targets[0]);
}