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];
   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);
      console.log('fileContents-----------------'+fileContents); //prints array with values
     console.log('fileContents-----------------'+fileContents); //prints empty array 


Any suggestion would be appreciated?.


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:

    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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.