IamGrooot
IamGrooot

Reputation: 1040

Calling a method once reader.onload is finished executing

I am trying to fire a method once my reader.onload finishes fetching the data and so that I can use that data in my method.

I am having hard time achieving that as you see in below snippet. Wherever I execute doOnLoad() method I am always getting undefined.

Please help

onFileChange(ev) {
    let workBook = null;
    let jsonData = null;
    const reader = new FileReader();
    const file = ev.target.files[0];
    reader.onload = event => {
      const data = reader.result;
      workBook = XLSX.read(data, { type: 'binary' });
      jsonData = workBook.SheetNames.reduce((initial, name) => {
        const sheet = workBook.Sheets[name];
        initial[name] = XLSX.utils.sheet_to_json(sheet);
        return initial;
      }, {});
      const dataString = JSON.stringify(jsonData);
      // console.log(dataString);
      configFile = dataString;
      //  doOnLoad(configFile);
    };
    reader.readAsBinaryString(file);
    doOnLoad(configFile);
}

  
doOnLoad(config) {
  console.log(config);  // Getting Undefined
}

Upvotes: 0

Views: 1692

Answers (1)

Vinay Sharma
Vinay Sharma

Reputation: 3777

Explanation

Let's consider a simple example where a file input is taken. To read the file, you would need reader to call readAsText() method. Once, the reader has loaded the file, it would fire a load event and the event would be handled by reader.onload.

So, in order to access the file content you need to write the code inside the event handler, i.e. reader.onload, else if you log fileContent just after reader.readAsText(), this line of code would execute before the reader even finished loading the file.

// Callback from a <input type="file" onchange="onChange(event)">

const onChange = (event) => {
  var file = event.target.files[0];
  var reader = new FileReader();

  let fileContent;

  reader.onload = (e) => {
    fileContent = e.target.result;

    // the file's text will be logged here
    console.log(fileContent);
  };

  reader.readAsText(file);
  console.log(fileResult); // undefined as reader didn’t finish loading the file
}

Solution

Move doOnLoad(configFile); inside reader.onload event handler.

// rest of the code

reader.onload = (event) => {
  // rest of the code
  configFile = dataString;
  doOnLoad(configFile);
};

reader.readAsBinaryString(file);

// rest of the code

Upvotes: 1

Related Questions