将普通功能更改为异步等待函数JavaScript
我正在尝试转换此功能是一个具有异步的函数,但是我找不到将等待等待的方法放入我的功能中,只需将其放置在等待的位置,它向我显示了控制台中的错误。 功能有什么作用?好吧,从输入中它检索了一个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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论