Asynchronous function call with await/async does not work in angular

Anna Lee

I am working with Angular, I have issues with asynchronous function call.

async ngOnInit() {
    this.a = new A();
    await this.a.method_A();

    this.b = new B(this.a);
    this.b.method_B(this.a.data);
}

export class A {
    data;
    async method_A() {
        observable$.subscribe((data) => { this.data = data });
    }
}

method_A is an asynchronous function, so it has to be ensured that after the method_A is completed, b has to be instantiated and the method_B has to be invoked. So, I used await/async like above, but I still find that instance b is created before method_A is completed. Is there a way for those steps to be performed sequentially?

mbojko
async method_A() {
    observable$.subscribe((data) => { this.data = data });
}

method_A doesn't wait for observable$ to emit. What is observable$, BTW? Does it emit only once? If so, you can easily convert it to the async-await pattern with

async method_A() {
    const data = await observable$.toPromise();
    this.data = data;
}

or, as toPromise is deprecated or will be soon,

async method_A() {
    const data = await firstValueFrom(observable$);
    this.data = data;
}

(And if observable$ emits more than once, I suggest ditching the async-await pattern and just using RxJS).

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related