how to call a function after the termination of another function in angular

  • A+
Category:Languages

I have 3 functions and I would like to call one after the other

openTryFunction(){     // function one     this.functionOne();     // after function one     this.functionTwo();     // after function two     this.functionTree(); } 

 


So you have three functions functionOne, functionTwo, and functionThree. There can be multiple PnCs of whether any of these functions is synchronous or asynchronous.

Let's generalize these scenarios into two main categories:

  1. All are synchronous: If this is the case, your code is going to run one after the other(synchronously).

  2. If any of the function is async: If this is the case, then the function that is async in nature should let the function that is supposed to be called after that, to know that it has terminated. In this case, you can either return a Promise/Observable from that async function. Or you can pass it a callback function that will get called after the async function finishes execution.

Two examples of this would be:

  1. Let's say all these functions are async in nature and all these functions return an Observable:

Then you should be writing it like:

openTryFunction() {   this.functionOne()     .subscribe(       () => this.functionTwo()               .subscribe(() => this.functionThree()                                  .subscribe(() => console.log('Function three terminated')))     ); } 
  1. If your functionOne and functionTwo returns a promise, then,:
openTryFunction() {   this.functionOne().then(() => {     this.functionTwo().then(() => this.functionThree());   }); }

Update:

You can also use async and await for a cleaner code. Here's a simple yet concrete example for the same:

import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http';  @Component({   selector: 'my-app',   templateUrl: './app.component.html',   styleUrls: [ './app.component.css' ] }) export class AppComponent  {   name = 'Angular';   users;    constructor(private http: HttpClient) {}    ngOnInit() {     this.getAllData();   }    getUsers() {     return this.http.get('https://jsonplaceholder.typicode.com/users')       .toPromise();   }    getUserPosts(userId) {     return this.http.get(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`)       .toPromise();   }    getPostComments(postId) {     return this.http.get(`https://jsonplaceholder.typicode.com/comments?postId=${postId}`)       .toPromise();   }    async getAllData() {     const users = await this.getUsers();     const posts = await this.getUserPosts(users[0].id);     const comments = await this.getPostComments(posts[0].id);      console.log(users);     console.log(posts);     console.log(comments);   }  }

Here's a StackBlitz for the same.

Hope that makes sense.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: