Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(); }
like image 855
Nikolas Soares Avatar asked Aug 31 '18 12:08

Nikolas Soares


2 Answers

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.

like image 127
SiddAjmera Avatar answered Sep 21 '22 16:09

SiddAjmera


If your functions are synchronous what you are doing is fine. If they are asynchronous and they return promises then you can string them together as so:

fOne()
  .then(() => {
    fTwo()
 } ).then(() => {
  fThree()
});

Alternatively you can use an async await.

async function tasks() {
  await fOne();
 await fTwo();
 await fThree();
}

Be sure to us try catch to handle exceptions.

If your functions return observables then concatMap is your friend.

fOne()
    .concatMap(() => fTwo())
    .concatMap(() => fThree());

Given your last function Does not return a promise you can omit await on the last call assuming you use async await.

like image 41
John Gallego Avatar answered Sep 22 '22 16:09

John Gallego