【问题标题】:How to get a response from a called function?如何从被调用函数中获得响应?
【发布时间】:2019-06-04 16:07:22
【问题描述】:

我想收到来自被调用函数的响应(真或假),以决定该函数是继续还是停止。查看以下代码以更好地理解:

function function1() {
    function2(); // call function2
    // after called function (here I need true or false, to decide if the function should stop or continue)
}

function function2() {
    if (condition === value) {
        // do something, give function1 a response to continue
    } else {
        // do something, give function1 a response to stop
    }
}

更新:

function function1() {
    console.log('call function2');
    function2(); // call function2
    // after called function (here I need true or false, to decide if the function should stop or continue)
    console.log('back from function2');
}

function function2() {
    if (condition === false) {
        console.log('condition === false');
        return;
    } 
}

【问题讨论】:

  • 这些函数是同步的吗?

标签: javascript jquery function callback


【解决方案1】:

语句中不需要 else。检查您的变量是否为假,如果是,它将返回,否则您的函数的其余部分将自动运行。

function function1() {
function2(); // call function2
// after called function (here I need true or false, to decide if the function should stop or continue)
}

function function2() {
if (condition === false) {
    return;
} 

}

【讨论】:

  • 感谢您的回复,但我需要返回一个值来决定 function1 是否应该继续。
  • 使用 return 将退出函数,这就是为什么你只说 return 而后面什么都没有。它没有返回任何值
  • 我刚刚用你的例子更新了这个问题。你能解释一下为什么我仍然从function2返回
  • 我现在要发布一个新的解决方案,我的朋友。
【解决方案2】:

如果function2是同步的,你可以直接返回:

function function1() {
  if(!function2()){
    return
  }; // call function2
  // after called function (here I need true or false, to decide if the function should stop or continue)
}

function function2() {
  if (condition === value) {
    return true;
  } else {
    return false;
  }
}

如果函数 2 执行异步操作并期望回调(您问题中的标记之一),那么编写一个使用 function2 并返回承诺的函数可能会更容易。

function function1(condition) {
  console.log('calling function 2');
  function2AsPromise(condition).then(function(
    function2Result
  ) {
    if (!function2Result) {
      console.log('function 2 result is false');
      return;
    }
    console.log('function 2 result is true');
  });
  console.log('exiting function 2');
}

function function2(condition, callback) {
  setTimeout(function() {
    if (condition) {
      callback(true);
    } else {
      callback(false);
    }
  }, 2000);
}

function function2AsPromise(condition) {
  return new Promise(function(resolve) {
    function2(condition, resolve);
  });
}

function1(false);

【讨论】:

    【解决方案3】:
    const function1 = check => {
       if (check === false) {
         return;
       } else {
       console.log("back from function2");
     }
    };
    
    
    function1(false) // console.log doesn't run
    function1(true) // console.log runs
    

    确保传入一个布尔值。

    【讨论】:

    • 如果这是您正在寻找的解决方案,请标记为答案
    猜你喜欢
    • 2017-07-03
    • 2019-05-23
    • 1970-01-01
    • 2021-10-19
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多