NadiaFaya
NadiaFaya

Reputation: 234

How to exit calling function in javascript

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...

Upvotes: 0

Views: 821

Answers (2)

Jason
Jason

Reputation: 564

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);
}

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191809

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.

Upvotes: 2

Related Questions