Terminate Javascript without error / exception

跟風遠走 提交于 2019-12-22 17:52:12

问题


I need to terminate the javascript from a function so that it doesn't execute the next block of codes and other functions called by the script, which follows the current function.

I found this existing question in SO : How to terminate the script in Javascript , where the solution is given as to trigger an error / exception which will terminate the script immediately.

But my case is different because, My purpose of terminating the script is to prevent an error which will come from the next functions, if the current function doesn't stop execution of the script. So, triggering another error to prevent an error is no way solving my purpose!

So, is there any other way of terminating the javascript instead of throwing an error / exception?

Please read my question properly before marking as duplicate, I have already explained why it doesn't solve my problem with the question I referred!.


回答1:


Since you're inside a function, just return.

Reading into your question a little more that it doesn't execute "other functions called by the script", you should return a boolean. For example, return false if you don't want the rest called, then wrap the remaining statements in an if:

function Foo() {
    if (weAreInLotsOfTrouble) {
        return false;
    }

    return true;
}

DoSomething();
DoSomethingElse();

if (Foo()) {
    DoSomethingDangerous();
}



回答2:


Try using jQuery.Callbacks() with parameter "stopOnFalse" ; jQuery.when() , jQuery .then()

var callbacks = $.Callbacks("stopOnFalse");

function a(msg) {
  var msg = msg || "a";
  console.log(msg);
  return msg
}
// stop callbacks here
function b() {
  var msg = false;
  console.log(msg)
  return msg
}
// `c` should not be called
function c() {
  var msg = new Error("def");
  console.log(msg)
  return msg
}

callbacks.add(a,b,c);

$.when(callbacks.fire())
.then(function(cb) {
  // `c` : `Error`
  if (cb.has(c)) {
    console.log("callbacks has `c`"
                , cb.has(c));
    // remove `c`
    cb.remove(c);
    console.log(cb.has(c));
    // empty `callbacks`
    cb.empty();
    // do other stuff
    cb.add(a);
    cb.fire("complete")
    
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>


来源:https://stackoverflow.com/questions/34735452/terminate-javascript-without-error-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!