英文:
My javascript code is executing after returning values to my event listener
问题
这是您提供的JavaScript代码的中文翻译部分:
使用JavaScript来读取Excel文件,我使用exceljs库,但我发现JavaScript函数会将响应返回给我的HTML事件监听器,并继续执行并读取文件内容。
我如何使这段代码在所有代码行完全执行后返回值?请帮忙,因为我是JavaScript的新手,是根据许多在线资源构建的这段代码。
readAndProcess(files) {
return new Promise(resolve => {
try {
const file = files[0];
let fileContent = [];
const fileReader = new FileReader();
fileReader.readAsArrayBuffer(file);
fileReader.onload = (e) => {
let result = e.target.result;
let columns = [];
let tableData = [];
let size;
if (result) {
// 创建工作簿并添加工作表
const wb = new ExcelJS.Workbook();
wb.xlsx.load(result).then(workbook => {
console.log(workbook, '工作簿实例');
workbook.eachSheet((sheet, id) => {
sheet.eachRow((row, rowIndex) => {
console.log(rowIndex, '行索引');
console.log(row);
if (rowIndex === 1) {
columns = Object.entries(row.values).map(([k, v]) =>
({
field: v,
headerText: v
})
);
} else {
const part = {};
let index = 0;
Object.entries(row.values).map(([k, v]) => {
part[columns[index].field] = v;
index++;
}
);
tableData.push(part);
};
});
});
});
resolve({
success: true,
result: {
name: file.name,
size: file.size,
type: file.type,
columns: columns,
tableData: tableData
},
error: {
detail: ''
}
});
} else {
resolve({
success: false,
error: {
detail: '空文件:' + result
}
})
}
}
} catch (err) {
resolve({
success: false,
error: {
detail: '读取文件时出错:' + err.detail
}
});
}
});
}
请注意,这是代码的翻译,不包含回答问题的部分。如果您有其他问题或需要进一步的帮助,请随时提出。
英文:
I'm making use of javascript to read the excel file with exceljs but I see that the javascript function is returning the response to my html event listerner and continuining execution and reading the content of file.
How can i make this code to return value after all lines of code are executed completely. Please help as I'm new to Javascript and have built this code by loooking at lot of online resources
readAndProcess(files) {
return new Promise(resolve => {
try {
const file = files[0];
let fileContent = [];
const fileReader = new FileReader();
fileReader.readAsArrayBuffer(file);
fileReader.onload = (e) => {
let result = e.target.result;
let columns = [];
let tableData = [];
let size;
if (result) {
// Create workbook & add worksheet
const wb = new ExcelJS.Workbook();
wb.xlsx.load(result).then(workbook => {
console.log(workbook, 'workbook instance');
workbook.eachSheet((sheet, id) => {
sheet.eachRow((row, rowIndex) => {
console.log(rowIndex, 'rowIndex');
console.log(row);
if (rowIndex === 1) {
columns = Object.entries(row.values).map(([k, v]) =>
({
field: v,
headerText: v
})
);
} else {
const part = {};
let index = 0;
Object.entries(row.values).map(([k, v]) => {
part[columns[index].field] = v;
index++;
}
);
tableData.push(part);
//console.log(tableData);
};
});
});
});
resolve({
success: true,
result: {
name: file.name,
size: file.size,
type: file.type,
columns: columns,
tableData: tableData
},
error: {
detail: ''
}
});
} else {
resolve({
success: false,
error: {
detail: 'Empty File : ' + result
}
})
}
}
} catch (err) {
resolve({
success: false,
error: {
detail: 'Error while reading file : ' + err.detail
}
});
}
});
}
}
答案1
得分: 1
你面临的问题是函数似乎在完成文件的读取和处理之前就返回结果了。
这是因为读取文件的函数(它被称为“异步”函数)不会停下来等待文件被读取。相反,它开始读取文件,然后立刻转向下一步。所以,在完成文件读取之前,函数已经开始执行下一步(即返回结果)。
你需要做的是告诉函数在返回结果之前等待文件被读取和处理。
在你的代码中,你已经告诉它等待文件被读取(使用onload
函数)。但你还需要告诉它在返回结果之前等待文件被处理(使用xlsx.load()
函数)。
以下是你可以做的事情:
-
查找你的代码中的部分,找到
wb.xlsx.load(result).then(workbook => {
。这是你开始处理文件的地方。 -
在这部分的末尾,你应该看到单词
resolve
,后面跟着一些花括号{}
。这是你告诉函数返回结果的地方。 -
将这个
resolve
部分(包括花括号内的所有内容)移动到xlsx.load()
函数的末尾。这将告诉函数在文件被读取和处理之前等待,然后再返回结果。
你只需要将resolve
部分移到正确的位置,你的函数就应该按预期工作。
英文:
The problem you're facing is that the function seems to be returning the result before it has finished reading and processing the file.
This is happening because the function that reads the file (it's called an "asynchronous" function) doesn't stop and wait for the file to be read. Instead, it starts reading the file and moves on to the next thing immediately. So, the function is moving on to the next thing (which is returning the result) before it has finished reading the file.
What you need to do is tell the function to wait until the file has been read and processed before returning the result.
In your code, you're already telling it to wait for the file to be read (using the onload
function). But you also need to tell it to wait for the file to be processed (using the xlsx.load()
function) before returning the result.
Here's what you can do:
-
Look for the part of your code that says
wb.xlsx.load(result).then(workbook => {
. This is where you start processing the file. -
At the end of this part, you should see the word
resolve
followed by some curly brackets{}
. This is where you're telling the function to return the result. -
Move this
resolve
part (with everything inside the curly brackets) to the end of thexlsx.load()
function. This will tell the function to wait until the file has been read and processed before returning the result.
You just need to move the resolve
part to the right place, and your function should work as expected.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论