Reputation: 877
Below code is problematic because it is not returning anything. How do I fix it?
public checkExistence(value: Item, tableName: string, schema: string): Promise<string>{
var result = "";
this.configData.forEach(element => {
if(element.key.tableName === tableName && element.checkExist != null){
let uiValue = value[element.key.columnName];
let refTargets = element.checkExist.split("|");
refTargets.forEach(target => {
let targetTableColumn = target.split(',', 2);
let table = targetTableColumn[0];
let column = targetTableColumn[1];
this.getRefData(schema,table,column).then((value: string[]) => {
if (!(value.indexOf(uiValue) > -1)){
result = result + table + "," + column + "|";
}
})
});
}
});
}
the whole purpose of this function is to check the existence of value[element.key.columnName]
in some column of some reference tables. There could be multiple reference tables to check (and hence refTargets.forEach
).
Ultimately I want this function to return a string that represents the list of table/columns which do not contain this value.
Found this similar case but not sure how to apply it to mine. Angular chaining promises from foreach loop
Starting to learn Angular and Promise, and appreciate if you can help.
IF you think this function could have been written in a better way, please let me know. I will accept it if it works :)
Upvotes: 0
Views: 906
Reputation: 7250
Try this.
Explaination: Following code
Promise
array where each Promise
will resolve to table + "," + column + "|"
string. Promise.all()
on created Promise
array. This will resolve to array of table + "," + column + "|"
strings. Promise
which will resolve to a string resulted concatanation of array of table + "," + column + "|"
strings in step 2.Code:
public checkExistence(value: Item, tableName: string, schema: string): Promise<string>{
// var result = "";
let promises:Promise<string>[] = [];
this.configData.forEach(element => {
if(element.key.tableName === tableName && element.checkExist != null){
let uiValue = value[element.key.columnName];
let refTargets = element.checkExist.split("|");
refTargets.forEach(target => {
let targetTableColumn = target.split(',', 2);
let table = targetTableColumn[0];
let column = targetTableColumn[1];
let promise: Promise<string> = this.getRefData(schema,table,column).then((value: string[]) => {
if (!(value.indexOf(uiValue) > -1)){
return /*result = result + */ table + "," + column + "|";
}
return "";
});
promises.push(promise);
});
}
});
return Promise.all(promises)
.then((results:string[])=>{
return results.join();
})
}
Upvotes: 2