The general use case for waiting for a function to finish is to use async-await
and Promise
. But somehow I can’t get it to work.
I have a directive and in this directive I have a public function like this:
getCellValue(
rowField: string,
rowValue: any,
columnField: string,
gridData?: any[]
): any {
setTimeout(() => {
if (gridData) {
return methods.getCellValuePrivate(
rowField,
rowValue,
columnField,
gridData
);
} else {
return methods.getCellValuePrivate(
rowField,
rowValue,
columnField,
this.config.gridData
);
}
});
}
It gets a value from the provided gridData
argument or from the this.config.gridData
. I have to use setTimeout
, because in the directive I do some data manipulating and with using setTimeout
I ensure, that I get the right data.
Now, in a component, where I use this directive, I simply look for it like this:
@ViewChild(EnhancedGridDirective) enhancedGridDirective!: EnhancedGridDirective;
And in ngAfterViewInit
I call the beforementioned function, f. e.:
const val = this.enhancedGridDirective.getCellValue(
'category',
'cat 2',
'feb'
);
console.log(val);
Of course I get undefined
in the console because of the setTimeout
in the function.
But if I change the function like this:
async getCellValue(
rowField: string,
rowValue: any,
columnField: string,
gridData?: any[]
): Promise<any> {
new Promise((resolve) => {
setTimeout(() => {
if (gridData) {
resolve(
methods.getCellValuePrivate(
rowField,
rowValue,
columnField,
gridData
)
);
} else {
resolve(
methods.getCellValuePrivate(
rowField,
rowValue,
columnField,
this.config.gridData
)
);
}
});
});
}
And in the ngAfterViewInit
then:
this.enhancedGridDirective
.getCellValue('category', 'cat 2', 'feb')
.then((v) => console.log(v));
I also get undefined
.
So, how to solve this issue?