I want to pass a promise as a parameter to another function, use it as a callback. The code I have works as follows
Component 1
function1() {
let promise: Promise<any>;
this.function2(promise);
promise.then(response => console.log(response));
}
Component 2
function2(promise) {
// Some Code
this.dialog.afterClosed().subscribe(data => {
promise.resolve(data);
});
}
Doing it this way produces an error in function 1, the error is: Cannot read property 'then' of undefined
Maybe what you want to do is something like:
function1() {
const promise: Promise = new Promise((resolve, reject) => {
this.function2(resolve);
});
promise.then(response => console.log(response));
}
function2(resolveFn: any) {
// Some Code
this.dialog.afterClosed().subscribe(data => {
resolveFn(data);
});
}
[UPDATE]: IMO, you should be doing it entirely with observables (no need for promises here):
function1() {
const afterClosed$: Observable<any> = this.function2();
afterClosed$.subscribe((response: any) => console.log(response));
}
function2(): Observable<any> {
// Some Code
return this.dialog.afterClosed();
}