Question

I am wondering if there is a clean way of implementing single exit point from a function in Javascript. In plain C one could simply use goto (Linux kernel - example source).

At the first sight one can use for, break and labels and exceptions.

1. For and labels

var retCode = 0;
single_exit:
for(var done=true;done;done=false)
{
    retCode = 1;
    break single_exit;
}
if(retCode !=0)
{
    console.log('error happened. exiting');
    return;
}

2. Exceptions

function SomeError () {
    this.retcode = 1;
}

SomeError.prototype = new Error();
try{
    if(someThing)
        throw new SomeError();
}
catch(e) {
  if (e instanceof SomeError) {
    return e.retcode;
  } else {
    throw e; 
  }
}

Are there any other(nicer) ways to handle this situation?

Was it helpful?

Solution 2

Uses promises.

Something like:

doSomething().then( function() { doSomethingElse().then( function(){ doYetAnotherThing() }) }); return 42;

where doSomething, doSomethingElse and doYetAnotherThing represent the individual steps that could 'break' (where break now means 'return a promise that is marked as failed). Each of them should return a promise. To make the code flatter you could alternatively do promise-chaining (here's a good video, in the context of Angular but you can ignore that part)

OTHER TIPS

I think that @Robert Levy has a very good point. A nice way of treating single exit point would imply promises:

Using q module from nodejs one can write:

var Q = require('q');
Q.fcall(function(){

})
.then(function(){

})
.then(function(){

})
.catch(function(err){
    //log them
})
.done(function(){
    do other stuff
})

I suppose the problem arises in a large function where you don't want to repeat operations like releasing resources.

Then a solution might be to define a simple function :

function yourFunction(){
     var resource = thing();
     function quit(){
         resource.release();
     }
     ... lot of code ...
     if (...) return quit();
     ...
}

Another solution might be to wrap your function in another one :

function bigFunWrapper(){
    var resource = thing();
    yourFunction();
    resource.release(); 
}

This solution, If you don't call it from multiple place, can be rewritten as an IIFE :

(function(){
    var resource = thing();
    yourFunction();
    resource.release(); 
})();

Depending on the precise use case, there's probably a better solution.

Now, before I answer this question, let me clearly state:

I consider this an ANTI-PATTERN! Not to be used, but an interesting approach to part of your question.

var returnCode = null;
do {
  // Do calculation
  if (condition) break;

  // do calculation
  if (condition2) break;



} while (false);
return returnCode;

Explanation: A do...while loop must run at least one time. The false condition makes sure it only runs once. The break exits the loop and jumps to the bottom.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top