wait for asynchronous functions to finish in Angular wait for asynchronous functions to finish in Angular angular angular

wait for asynchronous functions to finish in Angular


You can use basic promises with async/await.

async ngOnInit() {    await this.getUserProfile(); // <-- 1. change    // my-workplace depends on a private group and we need to fetch that group and edit    // the group data before we proceed and get the group post    if (this.isItMyWorkplace) {      this.getPrivateGroup();    }    this.loadGroupPosts();  }async getUserProfile() {    this._userService.getUser()      .subscribe((res) => {        this.user = res.user;        console.log('log user', this.user);        this.profileImage = res.user['profile_pic'];        this.profileImage = this.BASE_URL + `/uploads/${this.profileImage}`;        return true; // <-- this      }, (err) => {        this.alert.class = 'alert alert-danger';        if (err.status === 401) {          this.alert.message = err.error.message;          setTimeout(() => {            localStorage.clear();            this._router.navigate(['']);          }, 3000);        } else if (err.status) {          this.alert.class = err.error.message;        } else {          this.alert.message = 'Error! either server is down or no internet connection';        }        throw err;      });

}


You could instead leverage RxJS and use a switchMap something like this (syntax NOT checked):

getData(): Observable<string[]> {  return this._userService.getUser()    .pipe(      switchMap(userInfo=> {         return this.getPrivateGroup();      }),      catchError(this.someErrorHandler)    );}


One way to do is, return the Observable instead of subscribing in the getPrivateGroup()

getPrivateGroup() {    console.log('user check', this.user);    return this.groupService.getPrivateGroup(`${this.user.first_name}${this.user.last_name}`)  }

And then, subscribe to the data where you want the chain the this.loadGroupPosts()

     if (this.isItMyWorkplace) {          this.getPrivateGroup().subscribe(group => {          this.group = group; //you probably want to assign the group data          this.loadGroupPosts()});        }