I'm trying to use "workbook" variable outside "handleFile()" function. I know I can't return the workbook variable cause it's an async function and I tried to use promises but I don't know how to do it properly. Could you help me please! Please keep in mind that I'm a newbie Thanks!
var rABS = true; // true: readAsBinaryString ; false: readAsArrayBuffer
function handleFile(e) {
var files = e.target.files, f = files[0];
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
if(!rABS) data = new Uint8Array(data);
var workbook = XLSX.read(data, {type: rABS ? 'binary' : 'array'});
/* DO SOMETHING WITH workbook HERE */
};
if(rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);
}
input_dom_element.addEventListener('change', handleFile, false);
If you want to use a variable outside a function, you declare it outside the function. Make sure that the variable is either declared, or that you initialize it during the function call:
However, I'd suggest to use classes for your case, which will allow you to link variables and functions in a more logic and easy to maintain way. Your code can be re-written as such: