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:
All are synchronous: If this is the case, your code is going to run one after the other(synchronously).
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:
Then you should be writing it like:
openTryFunction() {
this.functionOne()
.subscribe(
() => this.functionTwo()
.subscribe(() => this.functionThree()
.subscribe(() => console.log('Function three terminated')))
);
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With