我有一组绑定(bind),它从代码之前和之后在函数内部获取触发器。就像下面这样:
function global() {
before(); // call all before binds here
//... mainFunction code...
after(); // call all after binds here
}
如果 before();
回调中的函数之一想要退出或停止 global()
进一步运行,我怎样才能停止它,而不检查返回值(value)观?
最佳答案
在不检查值 return
的情况下实现此目的的唯一方法ed,是通过 throw
引发异常正在阅读 error .
function before() {
throw new Error('Ending execution');
}
function after() {
console.log('Have you met Ted?');
}
function global() {
before();
// never reaches here
after();
}
global(); // Error: Ending execution
console.log('foo'); // not executed
如果您在某处调用了 global
并希望调用后的任何代码继续执行,则需要用 try..catch
将其包装起来,例如
function global() {
try {
before();
// never reaches here
after();
} catch (e) {
console.log(e); // log error. Leave this block empty for no action
}
}
global(); // Error logged
console.log('bar'); // still executed
关于Javascript 从子函数中退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16965287/