TypeScript/Angular 2 - 在另一个函数完成后调用一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40486765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript/Angular 2 - call a function after another completes
提问by Roka545
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?
我有两个要调用的函数,但我只想在第一个函数完成后调用第二个函数。我该怎么做?
Firstfunction:
第一个功能:
getDirectorySubfolders(node: any) {
console.log('Home:getDirectorySubfolders() entered...');
this._sdiService.getDirectoriesAtPath("Desktop")
.subscribe(res => {
this.nodeChildren = res;
});
}
Secondfunction:
第二个功能:
getChildren(node: any) {
console.log('Home:getChildren entered..');
return new Promise((resolve, reject) =>
{
setTimeout(() => resolve(this.nodeChildren.map((c) =>
{
return Object.assign({}, c, {});
})), 1000);
});
}
回答by Stefan Svrkota
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 ()
:
有两种简单的方法可以在第一个函数完成后调用第二个函数 - 您可以在this.nodeChildren = res;
完成参数下或使用完成参数()
:
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.
调用getDirectorySubfolders()
函数时,getChildren()
会在完成后调用 getDirectorySubfolders()
。请记住,如果您使用完成参数,即使发生错误,该函数也会被调用。