我有3个函数,我想一个接一个地调用
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(); }推荐答案
因此,您具有三个功能functionOne,functionTwo和functionThree.这些功能中的任何一个是同步的还是异步的,都可以有多个PnC.
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).
如果任何函数都是异步的:如果是这种情况,则本质上是异步的函数应让应该在此之后调用的函数知道它已经终止了.在这种情况下,您可以从该异步函数返回Promise/Observable.或者,您可以向其传递一个回调函数,该函数将在异步函数完成执行后被调用.
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.
这是两个示例:
那么您应该将其编写为:
Then you should be writing it like:
openTryFunction() { this.functionOne() .subscribe( () => this.functionTwo() .subscribe(() => this.functionThree() .subscribe(() => console.log('Function three terminated'))) ); }
openTryFunction() { this.functionOne().then(() => { this.functionTwo().then(() => this.functionThree()); }); }
更新:
您也可以将async和await用于更清晰的代码.这是一个简单但具体的例子:
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: './appponent.html', styleUrls: [ './appponent.css' ] }) export class AppComponent { name = 'Angular'; users; constructor(private http: HttpClient) {} ngOnInit() { this.getAllData(); } getUsers() { return this.http.get('jsonplaceholder.typicode/users') .toPromise(); } getUserPosts(userId) { return this.http.get(`jsonplaceholder.typicode/posts?userId=${userId}`) .toPromise(); } getPostComments(postId) { return this.http.get(`jsonplaceholder.typicode/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); } }
这里是 StackBlitz .
希望如此.
更多推荐
在Angular中终止另一个函数之后如何调用一个函数
发布评论