最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin11浏览0评论

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!

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!

Share Improve this question edited Oct 19, 2015 at 16:03 calipoop asked Oct 19, 2015 at 1:18 calipoopcalipoop 85211 silver badges33 bronze badges 3
  • 2 The outer function looks at the return value from the inner function and exits if the exit condition is met. – RobG Commented Oct 19, 2015 at 1:20
  • 3 The closest to what you are asking is throwing something. But your question is too vague. What you are asking can be done in several ways, and which one is right (if any) depends on what you are trying to acplish. This is very possibly an XY problem. – Amadan Commented Oct 19, 2015 at 1:21
  • No, this is impossible. – Bergi Commented Oct 19, 2015 at 1:21
Add a ment  | 

4 Answers 4

Reset to default 5

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 further 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 plex 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 parable 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.

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

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论