问题
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.
回答1:
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:
- Promisify the
FileReaderwithout adding specific logic (yourifcheck): keep that outside of it, so it remains generic - Use
Promise.allto map the file list to a new promise that will give the list of file contents. - Process the list of contents for the specific checks
- Return the new promise (
Promise.allor 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);
});
}
来源:https://stackoverflow.com/questions/54969731/call-then-only-after-method-returning-promise-is-finished