如何在 angular 中的另一个函数终止后调用一个函数 [英] how to call a function after the termination of another function in angular

查看:35
本文介绍了如何在 angular 中的另一个函数终止后调用一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 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(); }

推荐答案

所以你有三个函数 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:

那么你应该这样写:

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

  1. 如果您的 functionOnefunctionTwo 返回一个 promise,则:
  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.

希望这是有道理的.

这篇关于如何在 angular 中的另一个函数终止后调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆