mafortis
mafortis

Reputation: 7128

Angular wait for first function

I need to wait for my first function results before execute second one.

code

First function

getUser() {
    this.authService.user().subscribe(
        user => {
        this.user = user;
        console.log('current user 1: ', user);
        console.log('current user 2: ', this.user);
        }
    );
}

async ngOnInit() {
    this.socket.fromEvent('message').subscribe(async (message: any) => {
        if(this.user === undefined) {
            // first function called
            this.getUser();
            // before it finish this console log will fire, therefore it returns `undefined`
            console.log('this user: ', this.user);
        } else {
            //....
        }
    }
}

I need to hold my console call till this.getUser(); is done. How to do that?

Upvotes: 0

Views: 88

Answers (3)

Chetan Bansal
Chetan Bansal

Reputation: 1934

You can convert your getUser() method to a promise.. like this..

getUser():Promise<any>{
   return new Promise((resolve,reject) =>{
     this.authService.user().toPromise().then(user => {
       this.user = user;
       console.log('current user 1: ', user);
       console.log('current user 2: ', this.user);
       resolve(user);
     }).catch(err=> reject(err));
   });
}

Then in your ngOnInit()

async ngOnInit(){
  this.socket.fromEvent('message').subscribe((message: any) => {
    if(this.user === undefined) {
        // first function called
        await this.getUser().then(user=>{
           console.log('this user: ', user);
        });
    }
  });
}

Also, try using toPromise(), where you need data from an observer only once.. subscribing to an observer and then not unsubscribing it will lead to memory leaks..

Upvotes: 2

Anku Singh
Anku Singh

Reputation: 954

You need to use like below use await and i hope it will solve your problem

async ngOnInit() {
this.socket.fromEvent('message').subscribe(async (message: any) => {
    if(this.user === undefined) {
        // first function called
        await this.getUser();
        // before it finish this console log will fire, therefore it returns `undefined`
        console.log('this user: ', this.user);
    } else {
        //....
    }
}}

Upvotes: 0

Adrian Brand
Adrian Brand

Reputation: 21638

If you use combineLatest

combineLatest(this.authService.user(), this.socket.fromEvent('message'))
  .subscribe(([user, message]) => {
    // Both message and user are available at the same time
  });

Upvotes: 0

Related Questions