我正在寻找一种更聪明/更短的方法来进行以下操作:
function main() {
if (!otherfunction()) {
return; // exit main function
}
doMoreStuff();
...
}
相反,我希望“ main”函数中的退出由“ main”函数中调用的函数确定,例如:
function main() {
otherfunction(); // exit main function depending on what's going on in otherfunction()
doMoreStuff();
...
}
哦,亲爱的,哦,亲爱的,哦,亲爱的,哦,亲爱的-原谅我的$#x!这里。希望您明白我的意思。如果是这样,请随时提出一个更好的描述方式。
答案 0 :(得分:1)
您不能从内部函数中退出。您必须以某种方式在import { Subscription, combineLatest } from 'rxjs';
// ...
mySubscription: Subscription;
ngOnInit() {
this.mySubscription = combineLatest(
this.store.select('menuItems'),
this.route.fragment.pipe(
filter((fragment: string) => typeof fragment === 'string')
)
// DON'T USE ANY, type your data...!
).subscribe((data: [any, any]) => {
this.menuItems = data[0];
const fragment = data[1]
// do your thing...
})
}
ngOnDestroy() {
this.mySubscription.unsubscribe();
}
中捕获一些控制流。您可以选择几种方法。
首先,您可以使用上面概述的main()
语句:
if
这种方法完全可以接受并且可读性强。我在自己的生产代码中经常使用这种简单的方法。
第二,您可以使用异常并尝试/捕获控制:
function main() {
if(!otherFunction()) {
return;
}
doMoreStuff();
}
function main() {
try {
otherFunction(); // May throw an exception if you want to exit early.
doMoreStuff();
} catch(Exception $e) {
// Do nothing; just catch the exception and allow the rest of main() to finish.
}
}
不特别推荐这样做,但是您可以使用此有效选项。
最后,您可以使用条件表达式的短路求值:
// Alternatively
function main() {
otherFunction();
doMoreStuff();
}
try {
main();
} catch(Exception $e) {
// Do nothing; silently fail.
}
这也是一种完美有效的方法,您经常会在针对单行的shell脚本中看到它。
我个人的建议是使用function main() {
otherFunction() && doMoreStuff(); // if otherFunction() returns a non-"truthy" value, then doMoreStuff() won't execute.
}
语句来保持简单的提前返回模式,因为您的意图很明确,并且添加其他功能很容易。其他选项也可以使用,但您的意图并不清楚,因此可能难以在程序中添加功能。最终,决定权由您决定。
答案 1 :(得分:0)
如果您愿意结束整个PHP脚本的执行,则可以基于if语句在otherFunction()上使用exit,例如:
function doMoreStuff()
{
echo 'Test';
}
function otherfunction()
{
if(some condition) {
exit;
}
}
function main() {
otherfunction();
doMoreStuff();
}
在这种情况下,如果条件返回true,它将终止当前脚本,否则将回显“ Test”,这是doMoreStuff()函数的输出。
这是您想要实现的吗?