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

查看:137
本文介绍了在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:

那么您应该将其编写为:

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 .

希望如此.

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

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