0

Is there a way of exiting a function that has called the function that's currently executing?

An example would be:

function doOneTwoThree(){

    doStuff(1, print);

    doStuff(2, print);

    doStuff(3, print);

}

function doStuff(parameter, aFunction){

    if(parameter === 2) {
        //exit from doOneTwoThree
    }

    aFunction(parameter);
}

function print(something){

    console.log(something);

}

Another option would be to return an error in doStuff and check for that error in doOneTwoThree every time I call doStuff. But i would like not to have to check for it every time...

4
  • You could always just throw a javascript error on purpose. Commented Mar 8, 2013 at 15:25
  • return would return to the calling function, though? Or am I misunderstanding? Commented Mar 8, 2013 at 15:25
  • No... you are essentially trying to pop two stack frames off the call stack at one time and you cannot do that. Commented Mar 8, 2013 at 15:26
  • Exactly what @Daedalus said. I would think the real solution is to move the parameter check in method doOneTwoThree Commented Mar 8, 2013 at 15:30

2 Answers 2

2

You could use throw and catch the error throw in doOneTwoThree:

function doStuff(parameter, aFunction) {
    if (parameter === 2) {
        throw "error";
    }
}

function doOneTwoThree() {
    try {
        doStuff(1, print);
        doStuff(2, print);
    }
    catch (error) { /* handle here */ }
}

However, if you are not throwing an actual error/exception, you should not use this to control your code flow. Instead, you should check the return value of the doStuff call to confirm that you can continue on. If that sounds unclean to you, you could also do something like chain doStuff calls or call them in a loop that you can break out of based on the doStuff return value.

Sign up to request clarification or add additional context in comments.

Comments

0

Try something like this? return a token/magic value? (a string like 'eek' is probably a bad token, but it amused me, use an int instead )

function doOneTwoThree(){

    if (doStuff(1, print) === "eek") return;

    doStuff(2, print);

    doStuff(3, print);

}

function doStuff(parameter, aFunction){

    if(parameter === 2) {
        return "eek";
    }

    aFunction(parameter);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.