简体   繁体   中英

In Javascript, is it possible to stop outer function execution from inner function?

Is it possible to break out of an outer function from its inner function?

(function one(){
    var foo = (function two(){
        if(true){
            return true; //all good
        }else{
            //how can we break function one here?
    })();
    //extra statements only executed if foo is true
})();

No such thing as "return return" right? :P

UPDATE

Thanks all - as I suspected the "return return" functionality I was looking for is not possible. But with your input/tips I reworked my code and used a try/catch block. There a many ways to skin a cat in JS!

return only applies from within the function it's used.

What you can do is make two() return a boolean.
Than evaluate two() inside an if statement inside one()

 function two() { // Some logic here... var isError = true; // sometimes is false :) // Internals if (isError) { console.log("Something is wrong"); } // Finally return a boolean return isError; } (function one(){ // `two()` returns a boolean, true if there's an error. // `return` will stop furthere execution of `one()` if( two() ) return; console.log("This will not log if there was an error") })(); 

In your example code, it would be best for the outer function to test foo , but in more complex code, exceptions might be appropriate:

;(function() {
  var foo = (function() { return true })()
  if (!foo) return;
  console.log('reached because foo was true')
})()

;(function() {
  try {
    ;(function() {
      var foo = (function() { throw new Error('fail') })()
      /* only reached if an error wasn't thrown */
    })()
  }
  catch (error) {
    console.log('Something went wrong: ' + error)
  }
})()

Output:

reached because foo was true
Something went wrong: Error: fail

This desire might appear more often in JavaScript than in comparable languages because JavaScript's only way to provide scope is with a function body, and you have fewer control-flow options across function boundaries. But if you're using a self-executed function purely to provide a scope, and not keeping the function around to close over the variables, then just don't do that when you run into control-flow situations like this.

//how can we break function one here?

return false ?

 var div = document.querySelector("div"); var buttons = document.querySelectorAll("button"); var process = function process(value) { return (function one(val) { var foo = (function two(bool) { if (bool) { return true; //all good } else { return false //how can we break function one here? } })(val); //extra statements only executed if foo is true // if `foo` : `true` do stuff if (foo) alert(foo); // return `foo` return foo })(value) }; var fn = function(e) { div.innerHTML = process(e.target.textContent === "false" ? false : true); } buttons[0].onclick = fn; buttons[1].onclick = fn; 
 <button>true</button> <button>false</button> <div></div> 

The general idea of a function is that it will return a data type for the single function of which it resides. Return is just a language feature used to implement this idea of giving back data from the function. And so the notion of performing a return-return cannot be applied.

But in this paradigm, the problem you are solving is more related to Flow of Control . The solution you choose should be based on how you can most clearly express the idea in your code.

Depending on the reason you ask this question, if you are being challenged by a certain piece of logic in your application, and aren't just asking a technical question about the language, I would recommend posting a code sample which allows us to understand the intention of your goal. Since this is the key factor to choosing the best solution.

Of course you may implement a solution in all sorts of ways. Exceptions, statefulness, or functional solutions. But you need to choose the right tool for the job.

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