Reputation: 123
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);
}
});
}
I want to run the submitTC() method only after the readFile method is completely finished but .then(inside submitTCtoDB) is getting invoked early .
I think .then or promise is not used properly.
Desired functionality is to call the submitTC method only when readFile method is completed reading/splicing the files. Kindly help.
Upvotes: 3
Views: 893
Reputation: 350705
You have a resolve
call in a loop, but resolve
only has an effect when called the first time: once a promise resolves, that is its final state, and the then
callbacks are triggered. So that happens when the first file has been read, without waiting for any other files to be processed.
What you could do:
FileReader
without adding specific logic (your if
check): keep that outside of it, so it remains genericPromise.all
to map the file list to a new promise that will give the list of file contents. Promise.all
or the one chained on it) to the caller.Code:
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);
});
}
Upvotes: 2