submitTCtoDB() {
console.log("this.selectedFileList is: " + this.selectedFileList)
this.readFile().then(() => {
alert("ReadFile Finished now submit TC");
this.submitTC()
});
}
readFile() {
return new Promise((resolve,reject) => {
for (let i = 0; i < this.selectedFileList.length; i++) {
let file = this.selectedFileList[i];
alert("file in redafile" + file.name)
let fileReader = new FileReader();
fileReader.onload = () => {
this.fileContent = fileReader.result;
if (this.fileContent.indexOf("END DATA | BEGIN RESULTS") != -1) {
alert("Multiple testcases found in " + file.name + " file. Please separate/save testcases in Calc Builder. Then reimport");
const index: number = this.selectedFileList.indexOf(file);
if (index > -1) {
this.selectedFileList.splice(index,1);
}
console.log(this.fileContent);
}
resolve(this.fileContent);
}
fileReader.readAsText(file);
}
});
}
我只想在readFile方法完全完成后才运行commitTC()方法,但是.then(insideTCtoDB内部)会被提早调用.
我认为.then或promise没有正确使用.
最佳答案
您在循环中有一个resolve调用,但是只有在第一次调用时,resolve才会起作用:一次promise解析后,即为最终状态,然后触发回调.因此,在读取第一个文件时发生这种情况,而无需等待任何其他文件被处理.
您可以做什么:
>在不添加特定逻辑的情况下保证FileReader的合法性(如果需要,请检查):将其保留在其外部,因此它保持通用
>使用Promise.all将文件列表映射到将提供文件内容列表的新Promise.
>处理特定检查的内容列表
>将新的承诺(Promise.all或其上链接的一个)返回给呼叫者.
码:
submitTCtoDB() {
console.log("this.selectedFileList is: " + JSON.stringify(this.selectedFileList))
this.readFileList(this.selectedFileList).then((validList) => {
alert("ReadFile Finished now submit TC");
this.selectedFileList = validList;
this.submitTC()
});
}
readFileList(list) {
return Promise.all(list.map(file => this.readFile(file))).then(contents => {
return list.filter((file,i) => {
const fileContent = contents[i];
if (fileContent.indexOf("END DATA | BEGIN RESULTS") != -1) {
console.log("Multiple testcases found in " + file.name + " file. Please separate/save testcases in Calc Builder. Then reimport");
console.log(fileContent);
return false; // exclude this file
}
return true; // include this file
});
});
}
readFile(file) {
return new Promise(resolve => {
console.log("file in promiseFile: " + file.name);
const fileReader = new FileReader();
fileReader.onload = () => resolve(fileReader.result);
fileReader.readAsText(file);
});
}