簡體   English   中英

TypeScript / Angular 2 - 在另一個完成后調用一個函數

[英]TypeScript/Angular 2 - call a function after another completes

我有兩個函數需要調用,但我只想在第一個函數完成后調用第二個函數。 我該怎么做呢?

第一個功能:

getDirectorySubfolders(node: any) {
    console.log('Home:getDirectorySubfolders() entered...');

    this._sdiService.getDirectoriesAtPath("Desktop")
        .subscribe(res => {
            this.nodeChildren = res;
        });
}

第二功能:

getChildren(node: any) {
   console.log('Home:getChildren entered..');
   return new Promise((resolve, reject) =>
   {
       setTimeout(() => resolve(this.nodeChildren.map((c) =>
       {
           return Object.assign({}, c, {});
       })), 1000);
   });
}

完成第一個函數后,有兩種簡單的方法可以調用第二個函數 - 你可以在this.nodeChildren = res;下完成它this.nodeChildren = res; 或使用finish參數()

getDirectorySubfolders(node: any) {
    console.log('Home:getDirectorySubfolders() entered...');

    this._sdiService.getDirectoriesAtPath("Desktop")
        .subscribe(
         res => {
             this.nodeChildren = res;
             this.getChildren(); <-- here
         },
         err => {
             console.log(err);
         },
         () => {
             this.getChildren(); <-- or here
         });
}

當您調用getDirectorySubfolders()函數時,將在getDirectorySubfolders()完成后調用getChildren() getDirectorySubfolders() 請記住,如果使用finish參數,即使發生錯誤,也會調用該函數。

暫無
暫無

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

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