I'm working on converting an xlsx I get from a URL to a JSON object in the Browser.
This answer works --> https://stackoverflow.com/a/52237535/5079799
But, I can't get the code to wait for the reponse. All the answers online seem to be about images and/or using an input filereader, but I'm fetching a URL.
How I can wrap this all in a function that says:
- Get XLSX from URL
- Convert to JSON
- Return JSON
Here is what I've been messing with so far, but it always ends with the outside variables unset but the inside works correctly.
async function Outside_Test(){
var reso = await Get_JSON()
console.log('reso_out')
console.log(reso)
}
async function Get_JSON() {
var url = "http://myspreadsheet.xlsx"
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
//oReq.onload =
return oReq.send()
.then(function (oReq) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {
type: "binary"
});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
var reso = (XLSX.utils.sheet_to_json(worksheet, {
raw: true
}));
console.log('inside-reso')
return reso
})
}