簡體   English   中英

如何在角度中的另一個函數終止后調用函數

[英]how to call a function after the termination of another function in angular

我有3個功能,我想一個接一個地打電話

openTryFunction(){
    // function one
    this.functionOne();
    // after function one
    this.functionTwo();
    // after function two
    this.functionTree(); }

所以你有三個函數functionOnefunctionTwofunctionThree 可以存在多個PnC,無論這些功能中的任何一個是同步還是異步。

讓我們將這些場景概括為兩大類:

  1. 所有都是同步的 :如果是這種情況,您的代碼將一個接一個地運行(同步)。

  2. 如果任何函數是異步的 :如果是這種情況,那么本質上異步的函數應該讓那個應該被調用的函數知道它已經終止。 在這種情況下,您可以從該異步函數返回Promise / Observable。 或者您可以傳遞一個回調函數,該函數將在異步函數完成執行后調用。

兩個例子是:

  1. 假設所有這些函數本質上都是異步的,所有這些函數都返回一個Observable:

然后你應該寫它像:

openTryFunction() {
  this.functionOne()
    .subscribe(
      () => this.functionTwo()
              .subscribe(() => this.functionThree()
                                 .subscribe(() => console.log('Function three terminated')))
    );
}
  1. 如果你的functionOnefunctionTwo返回一個promise,那么:

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

更新:

您還可以使用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); } } 

這是一個相同的StackBlitz

希望有道理。

你可以使用Promise:

functionOne(): Promise<any> {
    return Promise.resolve((() => {
        // code here
        return 'from first'; // return whatever you want not neccessory
    })());
}

functionTwo(): Promise<any> {
    return Promise.resolve((() => {
        // code here
        return 'from second'; // return whatever you want not neccessory
    })());
}

functionThree() {
    // code here
}



this.functionOne().then(data1 => {
    console.log(data1);
    this.functionTwo().then(data2 => {
        console.log(data2);
        this.functionThree();
    });
});

如果你的功能是同步的,那你正在做的很好。 如果它們是異步的並且它們返回promise,那么你可以將它們串在一起,如下所示:

fOne()
  .then(() => {
    fTwo()
 } ).then(() => {
  fThree()
});

或者,您可以使用異步等待。

async function tasks() {
  await fOne();
 await fTwo();
 await fThree();
}

一定要嘗試catch來處理異常。

如果你的函數返回了observables,那么concatMap就是你的朋友。

fOne()
    .concatMap(() => fTwo())
    .concatMap(() => fThree());

鑒於你的最后一個函數不返回一個promise你可以在最后一次調用時省略await,假設你使用async await。

你可以嘗試這個,

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

功能3將在2完成時運行,2將在1完成時運行。

如果函數返回一個observable,那么只需在subscribe調用下一個函數。 否則,從每個函數返回一個promise。 然后你可以鏈接被調用的函數。

functionOne() {
    return new Promise((resolve) => {
        //
        // Your function implementation
        //
        // Resolve the promise at the end
        resolve(); 
    });
}

functionTwo() {
    return new Promise((resolve) => {
        //
        // Your function implementation
        //
        // Resolve the promise at the end
        resolve(); 
    });
}

functionThree() {
    return new Promise((resolve) => {
        //
        // Your function implementation
        //
        // Resolve the promise at the end
        resolve(); 
    });
}


openTryFunction(){
    // function one
    this.functionOne().then(() => {
        // after function one
        this.functionTwo().then(() => {
            // after function two
            this.functionTree(); 
        });        
    });
}

查看此示例,其中每個函數返回一個Observable ,執行序列由concat函數控制。

export class AppComponent implements OnInit {
  name = 'Angular';
  values = [];

  first(): Observable<string> {
    return of('first');
  }

  second(): Observable<string> {
    return of('second');
  }

  afterSecond(): Observable<string> {
    return of('secondish');
  }

  third(): Observable<string> {
    return of('third');
  }

  ngOnInit() {
    let sequence = concat([
      this.first, 
      this.second, 
      this.afterSecond, 
      this.third]);

    sequence.subscribe(currentFunction => {
      currentFunction().subscribe(value => {
        this.values.push(value);
      })
    });
  }

}

我喜歡concat函數,因為它構建了我們添加到列表中的函數的Observable

注意,這個調用sequence.subscribe(currentFunction中的每個值currentFunction將是一個功能,並且為了有它的實際價值,因為它是一個Observable你需要訂閱。

請在此處查看完整示例: https//stackblitz.com/edit/angular-functions-in-sequence?file = ssc %%Fapp%2Fapp.component.ts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM