简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM