0

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?

3 Answers 3

2

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..

Sign up to request clarification or add additional context in comments.

1 Comment

Mixing promises and RxJs is frowned upon by many. It is not wrong, but many people including myself would rather see a pure RxJs solution.
0

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
  });

5 Comments

I think not, see as my code is in ngOnInit if I do your way it will call for both of these instantly, I need to call for user ONLY if I have socket event Or i'm mistaking?
If one call relies on another you can use switchMap this.socket.fromEvent('message').pipe(switchMap(message => functionThatReturnsAnObservable(message)))
sorry I am not that pro in angular and this half codes just makes me more confused :D
My advise is that you are not ready to start learning Angular yet, Angular is built upon RxJs. Stop learning Angular for a day or two and go get familiar with RxJs. I wish somebody gave me this advise in the beginning as the apps I first wrote a few years ago would have been structured very differently if I knew more about RxJs at the time. Yes it seems confusing at first but it is the greatest improvement to asynchronous development in a long time.
rxmarbles.com is a great site that made many of the concepts click once I saw them visually
0

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 {
        //....
    }
}}

3 Comments

Thanks, after build finish i'll let you know the result
getUser doesn't return anything, it would need to return a promise for await to work
as Adrian mentioned it returns nothing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.