Call Then Only After Method Returning Promise Is Finished
submitTCtoDB() { console.log('this.selectedFileList is: ' + this.selectedFileList) this.readFile().then(() => { alert('ReadFile Finished now submit TC'); this.submi
Solution 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
FileReader
without adding specific logic (yourif
check): keep that outside of it, so it remains generic - Use
Promise.all
to 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.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) {
returnPromise.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);
returnfalse; // exclude this file
}
returntrue; // include this file
});
});
}
readFile(file) {
returnnewPromise(resolve => {
console.log("file in promiseFile: " + file.name);
const fileReader = newFileReader();
fileReader.onload = () =>resolve(fileReader.result);
fileReader.readAsText(file);
});
}
Post a Comment for "Call Then Only After Method Returning Promise Is Finished"