将普通功能更改为异步等待函数JavaScript

发布于 2025-02-09 21:17:17 字数 1240 浏览 1 评论 0原文

我正在尝试转换此功能是一个具有异步的函数,但是我找不到将等待等待的方法放入我的功能中,只需将其放置在等待的位置,它向我显示了控制台中的错误。 功能有什么作用?好吧,从输入中它检索了一个excel文件,它以二进制读取它,我将其通过event.target.result在一个称为数据的变量中通过,然后使用xlsx读取。阅读二进制类型最后是生成JSON。因为我要重复使用代码加载不同的文件,所以我需要延迟文件读数,这就是为什么我需要将函数转换为异步等待

我的代码下面的代码

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;
    }
  }
}

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;
    }
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文