我想停止返回第一个功能。请看我的示例以更好地理解:
function function1() {
function2();
console.log('back after called function'); // shoudn't log if condition is true
}
function function2() {
if (condition === true) { // if condition is true, stop right here (no callback to function1)
return false;
} else {
// callback is allowed
}
}
答案 0 :(得分:0)
使用三元运算符。
function2() ? false : console.log('back after called function');
您也可以添加更多行-使用IIFE。
function2() ? false : (() => {
console.log('back after called function');
//More code
})();
答案 1 :(得分:0)
简单就抛出并捕获错误
function function1() {
try{
function2();
console.log('back after called function'); // shoudn't log if condition is true
}catch(e){
console.log(e.message);
}
}
function function2() {
if (1 === 1) { // if condition is true, stop right here (no callback to function1)
throw new Error('forced stopped');
} else {
// callback is allowed
}
}
<!DOCTYPE html>
<html>
<body onLoad="function1()">
</body>
</html>
答案 2 :(得分:0)
最简单的方法应该是:
function function1() {
if (function2()) {
console.log('back after called function');
}
}
正如Jack Bashford所建议的(但写法错误),您可以使用三元运算符:
function function1() {
function2()? console.log('back after called function') : return;
}
或者,对于更复杂的代码处理,您可以使用回调函数:
function function1() {
function2(function(error) {
if (!error) {
console.log('back after called function');
}
});
}
function function2(callback) {
if (condition === true) {
callback("Error: condition false");
} else {
callback(null);
}
}
编辑:
使用我的最后一个选项,您可以完全按照您的要求进行操作:不要返回到function1:
function function1() {
function2(function() {
console.log('back after called function');
});
}
function function2(callback) {
if (condition === true) {
return;
} else {
callback();
}
}
但是我认为,出于良好实践的考虑,您应该始终调用回调函数。
答案 3 :(得分:0)
我认为function2不能不返回到function1
function function1() {
if (function2()) return;
console.log('back after called function'); // shoudn't log if condition is true
}