如何停止 return 以外的节点 js 中的代码执行

how to stop the execution of code in node js other than return

所以我想在某个事件发生时停止代码但不想使用 return 因为该函数应该是 return 一个值,如果我用它来停止代码它会返回一个未定义的值 例如这是我需要的

  foo =() =>{
     if(event){
        //stop code 
    }else {
    return "Value"
    
    }

}

我不想做的事情

    bar =() =>{
    if(event){
    // dont want to use it since it would return an undefined value 
     return ;
    }else{
    
    return "Value" ; 
    }

}

但是您为什么不希望 undefined 被 return 编辑?我的意思是......即使你有一个 return 完全没有价值的功能,它仍然会 return undefined.

const a = (function(){})();
console.log(a); // undefined

这只是 javascript 的默认行为。但是,如果您希望由于某种情况而停止执行,我对您最好的建议是抛出异常并进行处理。

const MyFunction = (b) => {
  if (b) throw 'You shall not pass!';

  return 'I shall pass! This time...';
};

try {
  console.log(MyFunction(false));
 console.log(MyFunction(true));
} catch(err) {
  console.log(err);
}