从reader.readAsArrayBuffer返回数据



我有以下代码。我试图将uploadData数组返回到hello变量。然而,它作为一个空数组返回。控制台日志打印出正确的数据数组,如下所示:{name: 'bob'},但在读取器之后。readAsArrayBuffer行,它变成空白。有人知道为什么吗?

Hello = validateSpreadsheet(file, rows)
validateSpreadsheet = function (fileUpload, templateRows) {
let uploadData = [];
for (const file of fileUpload.files) {
const fileExtension = file.name.split(".").pop();
let valid = false;
if (fileExtension === "csv") {
valid = true;
}
if (!valid) {
throw "Unsupported file type, file must be 'of type .csv";
}
const reader = new FileReader();
reader.onload = async (e) => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, {
type: "array",
cellDates: true,
dateNF: "dd/mm/yyyy",
});
if (workbook.SheetNames.length === 0) {
console.error("No sheets");
}
for (const sheetName of workbook.SheetNames) {
const rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {
defval: null,
});
for (let row of rows) {
uploadData.push(row);
}
}
console.log(uploadData);
};
reader.readAsArrayBuffer(file);
return uploadData;
}
};

uploadData不更新,直到您的reader.onload函数被调用(它被异步调用)。因此,为了解决这个问题,您可以向validateSpreadsheet传递一个回调函数,以接收正确的uploadData

validateSpreadsheet(file, rows, function (uploadData) {
// do something with the data here
console.log(uploadData);
});
validateSpreadsheet = function (fileUpload, templateRows, callback) {
let uploadData = [];
for (const file of fileUpload.files) {
const fileExtension = file.name.split(".").pop();
let valid = false;
if (fileExtension === "csv") {
valid = true;
}
if (!valid) {
throw "Unsupported file type, file must be 'of type .csv";
}
const reader = new FileReader();
reader.onload = async (e) => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, {
type: "array",
cellDates: true,
dateNF: "dd/mm/yyyy",
});
if (workbook.SheetNames.length === 0) {
console.error("No sheets");
}
for (const sheetName of workbook.SheetNames) {
const rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {
defval: null,
});
for (let row of rows) {
uploadData.push(row);
}
}
console.log(uploadData);
callback(uploadData);        // the correct `uploadData` will be passed to your callback here
};
reader.readAsArrayBuffer(file);
return uploadData;
}
};

相关内容

  • 没有找到相关文章

最新更新