Roka545 Roka545 - 26 days ago 13
TypeScript Question

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

Answer

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
        },
        () => {
            this.getChildren(); <-- or here
        });
}

When you call getDirectorySubfolders() function, getChildren() will be called after completion of getDirectorySubfolders().

Comments