Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript/Angular 2 - call a function after another completes

I have two functions that I would like to call, but I only want to call the second one after the first one completes. How do I go about doing that?

First function:

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

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

Second function:

getChildren(node: any) {
   console.log('Home:getChildren entered..');
   return new Promise((resolve, reject) =>
   {
       setTimeout(() => resolve(this.nodeChildren.map((c) =>
       {
           return Object.assign({}, c, {});
       })), 1000);
   });
}
like image 872
Roka545 Avatar asked Nov 08 '16 12:11

Roka545


1 Answers

There are two simple ways to call your second function after first one is finished - you can do it under this.nodeChildren = res; or use finish parameter ():

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

When you call getDirectorySubfolders() function, getChildren() will be called after completion of getDirectorySubfolders(). Keep in mind that if you use finish parameter, the function will get called even if error occurs.

like image 102
Stefan Svrkota Avatar answered Sep 24 '22 14:09

Stefan Svrkota