且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Angular中终止另一个函数之后如何调用一个函数

更新时间:2022-12-29 10:21:23

因此,您具有三个功能functionOnefunctionTwofunctionThree.这些功能中的任何一个是同步的还是异步的,都可以有多个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:

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

  1. 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.

这是两个示例:

  1. 让我们说所有这些函数本质上都是异步的,并且所有这些函数都返回一个Observable:

那么您应该将其编写为:

Then you should be writing it like:

openTryFunction() {
  this.functionOne()
    .subscribe(
      () => this.functionTwo()
              .subscribe(() => this.functionThree()
                                 .subscribe(() => console.log('Function three terminated')))
    );
}

  1. 如果您的functionOnefunctionTwo返回承诺,则:
  1. If your functionOne and functionTwo returns a promise, then,:

openTryFunction() {
  this.functionOne().then(() => {
    this.functionTwo().then(() => this.functionThree());
  });
}

更新:

您也可以将asyncawait用于更清晰的代码.这是一个简单但具体的例子:

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

}

这里是 StackBlitz .

希望如此.