I'm not entirely sure how to fix this. My goal is to call the filereader on the excel doc and then be able to retrieve additional information after the file has been parsed. But sync FileReader is async, when i go to access the obj properties like obj.workbook, it always prints null. How do i resolve this?
So in the code below you'll notice after i call 'parse()' i call console.log('obj.workbook:', obj.workbook) which prints null in the console. I would expect it to print the workbook value assigned in the parse method called prior.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>
<script>
class ExcelDoc {
constructor(file) {
this.file = file;
this.workbook = null;
}
// Methods
parse() {
var reader = new FileReader();
reader.onload = () => {
this.workbook = XLSX.read(reader.result, {
type: 'binary'
});
};
reader.onerror = function(ex) {
console.log(ex);
reader.abort();
};
reader.readAsBinaryString(this.file);
}
}
function handleFileSelect(evt) {
var files = evt.target.files;
var obj = new ExcelDoc(files[0]);
obj.parse()
console.log('obj.file:', obj.file)
console.log('obj.workbook:', obj.workbook)
console.log('obj:', obj)
}
</script>
<form enctype="multipart/form-data">
<input id="upload" type=file name="files[]">
Sheets
<select id="sheetSelector">
<option>Choose a sheet</option>
</select>
</form>
<textarea class="form-control" rows=35 cols=120 id="xlx_json"></textarea>
<script>
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>