如何在角度中的另一个函数终止后调用函数

Nik*_*res 9 typescript angular angular6

我有3个功能,我想一个接一个地打电话

openTryFunction(){
    // function one
    this.functionOne();
    // after function one
    this.functionTwo();
    // after function two
    this.functionTree(); }
Run Code Online (Sandbox Code Playgroud)

Sid*_*era 11

所以,你有三种功能functionOne,functionTwo以及functionThree.可以存在多个PnC,无论这些功能中的任何一个是同步还是异步.

让我们将这些场景概括为两大类:

  1. 所有都是同步的:如果是这种情况,您的代码将一个接一个地运行(同步).

  2. 如果任何函数是异步的:如果是这种情况,那么本质上异步的函数应该让那个应该被调用的函数知道它已经终止.在这种情况下,您可以从该异步函数返回Promise/Observable.或者您可以传递一个回调函数,该函数将在异步函数完成执行后调用.

两个例子是:

  1. 假设所有这些函数本质上都是异步的,所有这些函数都返回一个Observable:

然后你应该写它像:

openTryFunction() {
  this.functionOne()
    .subscribe(
      () => this.functionTwo()
              .subscribe(() => this.functionThree()
                                 .subscribe(() => console.log('Function three terminated')))
    );
}
Run Code Online (Sandbox Code Playgroud)
  1. 如果你的functionOne并且functionTwo返回一个承诺,那么:

openTryFunction() {
  this.functionOne().then(() => {
    this.functionTwo().then(() => this.functionThree());
  });
}
Run Code Online (Sandbox Code Playgroud)

更新:

您还可以使用asyncawait更清晰的代码.这是一个简单而具体的例子:

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);
  }

}
Run Code Online (Sandbox Code Playgroud)

这是一个相同的StackBlitz.

希望有道理.


Moh*_*ian 0

你可以试试这个

openTryFunction(){
this.functionOne().then(()=>{this.functionTwo().then(() => {this.functionTree()})})}
Run Code Online (Sandbox Code Playgroud)

函数 3 将在 2 完成时运行,2 将在 1 完成时运行。

  • 仅当第一个和第二个函数返回 Promise 时。 (3认同)