0

I'm trying to convert this function is a function with async await, but I can't find a way to put the await inside my function, simply where I put the await it shows me an error in the console. what does the function do? well, from an input it retrieves an excel file, it reads it in binary, I pass it in event.target.result in a variable called data, then it reads with XLSX.read the binary type that is sent to a variable called workbook and finally it is generate the json. Because I am going to reuse the code to load different files, I need to delay the file reading, that's why I need to convert the function to async await

My code below

document.getElementById('uploadBud').addEventListener('click', () => {
  let selectedFile = document.getElementById('importBUDid').files[0];

  Get_DataXls(selectedFile).then(arreglo => {

    alert('Ready');
  });

});

async function Get_DataXls(selectedFile) {
  let jsonObj;
  if (selectedFile) {
    let fileReader = new FileReader();
    fileReader.readAsBinaryString(selectedFile);
    fileReader.onload = (event) => {
      //console.log(event.target.result);
      let dato = event.target.result;
      let workbook = XLSX.read(dato, {
        type: "binary"
      });
      //console.log(workbook.Strings);
      workbook.SheetNames.forEach(sheet => {
        let rowObject = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheet]);

        //console.log(rowObject);
        jsonObj = rowObject;
      });
      console.log(jsonObj);
      return jsonObj;
    }
  }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
madison_sg
  • 11
  • 1
  • https://stackoverflow.com/questions/48172934/error-using-async-and-await-with-filereader – epascarello Jun 22 '22 at 18:36
  • Where did you try to put `await`? Post the code with the problem, not just the original code. – Barmar Jun 22 '22 at 19:16
  • I did put the await exactly here: fileReader.onload = await (event) => { //console.log(event.target.result); let dato = event.target.result; let workbook = XLSX.read(dato, { type: "binary" }); – madison_sg Jun 22 '22 at 19:30

0 Answers0