Reputation:
I wrote these simple code,
function a()
{
function b()
{
function d()
{
if (/*required condition goes here and should stop execution of
function a()*/)
{
return
}
}
d()
}
function c()
{
alert ('c')
};
b();
c();
}
What I expected is the execution aborts when it meet the required condition on function d()
and cancelling the execution of function c()
. Otherwise, it runs the remaining function after executing function b()
.
How can I do that?
Edit: What I actually want to know wheter if the 'return' key colud terminate immediately for the outer function like 'Exit Sub' on VB.Net
Upvotes: 2
Views: 67
Reputation: 386868
You could use the return value for the inner function and use it as flag.
function a() {
function b() {
function d() {
console.log('in d');
if (true) {
return;
}
return true;
}
console.log('in b');
return d();
}
function c() {
console.log('in c');
alert('c');
}
console.log('in a');
console.log(b() && c());
}
a();
Upvotes: 0
Reputation: 1075755
You'd pass the information that processing should stop out of d
and out of b
and use it to determine whether to call c
:
function a() {
function b() {
function d() {
if (/*some condition*/) {
return false; // ***
}
return true; // ***
}
return d(); // ***
}
function c() {
alert('c')
};
if (b()) { // ***
c(); // ***
} // ***
}
Alternately, you could have d
throw:
function a() {
function b() {
function d() {
if (/*some condition*/) {
throw new Error(); // ***
}
return;
}
d();
}
function c() {
alert('c')
};
b();
c();
}
...but then a
would throw rather than completing normally (though you could add a try
/catch
). Also, throwing is relatively expensive and not for normal branching purposes.
Upvotes: 1