5

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

1 Answer 1

9

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.

3
  • 1
    Hey @Stefan Svrkota, I tried your solution and it looks like, in the most recent version of angular, you are passing in an error method for the () section, not a complete method. you need to add something like this: this._sdiService.getDirectoriesAtPath("Desktop") .subscribe(res => { this.nodeChildren = res; this.getChildren(); <-- here }, null, // doesn't have to be null, just another parameter () => { this.getChildren(); <-- or here });
    – Ethan
    Sep 27, 2018 at 13:53
  • 1
    @Ethan That's true, I edited my answer so it doesn't create any confusion for the further readers. Thank you so much for letting me know! Sep 27, 2018 at 14:35
  • 1
    you are so welcome! Happy to help, this post helped me make a step in the right direction :D
    – Ethan
    Sep 27, 2018 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.