I am probably looking for something that is impossible, but anyway let's give it a try. Please consider the following pseudo code that is performing some conditional, remote operation, that executes callback upon completion. But the code in the callback needs to be executed even if remote operation was not neccessary:
if (needsToSave)
{
performRemoteOperation(operationParameters, function() {
doSomeCleanup();
doSomeMoreCleanup();
setSomeStatus();
});
}
else
{
doSomeCleanup();
doSomeMoreCleanup();
setSomeStatus();
}
I find this code particularly ugly and unmanageable. It is easy to omit a change done to callback block in relevant unconditional block. There is an obvious solution of wrapping code in some named function, but it isn't anonymous inline code anymore then. :-)
The best I can think of is to wrap whole code in some conditional caller:
function conditionalCall(condition, action, callback)
{
if (condition)
action(callback)
else
callback()
}
Then my code would fold to:
conditionalCall(needsToSave,
function(_callback) {
performRemoteOperation(operationParameters, _callback)
},
function()
{
doSomeCleanup();
doSomeMoreCleanup();
setSomeStatus();
}
);
...but I am not absolutely sure, whether this is more readable and manageable. Especially when lots of local/remote/callback parameters/closure variables get involved or one needs to "embed" one remote call within another call's callback. I hope there is some better syntax that could be used in such a scenario.