0

Unable to print fileContents array values within a function. On upload file, i want to store file content in a js array then use whenever i need with in a function(like if condition below). But after the doc.onload = function() scope, the fileContents value is not available. it prints empty array.

projects:function(component, event, helper){
var fileName = [];
 var fileContents =[];
var fileInput = component.find("fileId");
if(fileInput && !Array.isArray(fileInput)){
  var f = fileInput.get("v.files");     
  var file = f[0][0];
   fileName.push(file.name);
   var fileContent;
  var doc= new FileReader();    
  doc.onload = function() {
    var self=this;
       fileContent = doc.result;
    var base64 = 'base64,';
      var dataStart = fileContent.indexOf(base64) + base64.length;
      fileContent = fileContent.substring(dataStart);
      fileContents.push(fileContent);
      console.log('fileContents-----------------'+fileContents); //prints array with values
    };
    filer.readAsDataURL(file);
  if(somecondition){
     console.log('fileContents-----------------'+fileContents); //prints empty array 
   }

}

Any suggestion would be appreciated?.

1 Answer 1

0

You've misunderstood how JavaScript works. When you call readAsDataURL, it is not called immediately, but instead called asynchronously. That means that the code after that:

if(somecondition){
    console.log('fileContents-----------------'+fileContents); //prints empty array 
}

Actually runs before the onload function, despite occurring later in the same function.

Let me demonstrate with an very short example how asynchronous calls work:

console.log('Point 1');
setTimeout(() => console.log('Point 2'));
console.log('Point 3');

The output will be:

Point 1
Point 3
Point 2

However, in the interest of being Lightning-specific, I suggest that you always use an attribute to store values that will exist between life cycles. This will make sure that you can access the data when you need to.

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.