Say I have this function (psuedo-code) :
function Foo() {
let varThatRequiresCleanup = //something
if(condition1) {
return Error1;
}
if(condition2) {
return Error2;
}
if(condition3) {
return Error3;
}
//etc.. more ifs and important code.
varThatRequiresCleanup.CleanUp();
return Success;
}
Coming from the C++ & C world I would just implement the cleaning up in the destructor or use a goto but JavaScript doesn't have either.
How would I go about calling CleanUp() whenever Foo() returns?
Is the only method to call CleanUp() in every if that I return in?
One alternative could be to use a function for the repeating code :
function Foo() {
let varThatRequiresCleanup = //something
function CleanUpAndReturn(returnValue) {
varThatRequiresCleanup.CleanUp();
return returnValue;
}
if (condition1) { return CleanUpAndReturn(Error1); }
if (condition2) { return CleanUpAndReturn(Error2); }
if (condition3) { return CleanUpAndReturn(Error3); }
//etc.. more ifs and important code.
return CleanUpAndReturn(Success);
}
You can use a try-finally block:
function Foo() {
let varThatRequiresCleanup = //something
try {
if(condition1) {
return Error1;
}
if(condition2) {
return Error2;
}
if(condition3) {
return Error3;
}
//etc.. more ifs and important code.
return Success;
} finally {
varThatRequiresCleanup.CleanUp();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With