我正在使用FileReader解析我的csv数据并仅获取标头。 我需要检查标题,并根据返回值执行进一步的操作。
private checkIfValidFile(file){
var isValidFile = false;
var fileContent = new FileReader();
fileContent.readAsText(file);
fileContent.onload = () => {
let text = fileContent.result;
var data = text.split("\n");
var headers = data[0].split(",");
//fileHeaders = headers;
console.log(headers);
if (headers.indexOf('"File Name"') > -1) {
isValidFile = true;
}
};
return isValidFile
}
private uploadFiles(files: any) {
for (let index = 0; index < files.length; index++) {
var isValidFile = this.checkIfValidFile(files[index]);
if(isValidFile){
//Execute some lines
}
}
}
但是返回值在onload之前返回。我该怎么办?
答案 0 :(得分:0)
使用“承诺”来达到这样的目的:
private checkIfValidFile(file):Promise<boolean>{
var fileContent = new FileReader();
fileContent.readAsText(file);
return new Promise((resolve,reject)=>{
fileContent.onload = () => {
let text = fileContent.result;
var data = text.split("\n");
var headers = data[0].split(",");
//fileHeaders = headers;
console.log(headers);
if (headers.indexOf('"File Name"') > -1) {
resolve(true);
}
resolve(false);
};
});
}
private uploadFiles(files: any) {
for (let index = 0; index < files.length; index++) {
this.checkIfValidFile(files[index]).then((isValidFile)=>{
if(isValidFile){
//Execute some lines
}
});
}
}
答案 1 :(得分:0)
使用承诺如何?
喜欢:
private checkIfValidFile(file): Promise<boolean> {
return new Promise((resolve, reject) => { // RETURN PROMISE FFORM YOUR FUNC
try {
var isValidFile = false;
var fileContent = new FileReader();
fileContent.readAsText(file);
fileContent.onload = () => {
let text = fileContent.result;
var data = text.split("\n");
var headers = data[0].split(",");
//fileHeaders = headers;
console.log(headers);
if (headers.indexOf('"File Name"') > -1) {
isValidFile = true;
resolve(isValidFile);
}
};
} catch (error) {
reject(error);
}
});
}
private uploadFiles(files: any) {
for (let index = 0; index < files.length; index++) {
this.checkIfValidFile(files[index]).then((isValidFile) => {
if (isValidFile) {
//Execute some lines
}
});
}
}