如何'return'从父函数'

How to 'return' out of a parent function from it's child?

本文关键字:函数 return 如何      更新时间:2023-09-26

我经常在项目中使用verifyInput函数来确保从用户那里获得有效的输入。不时地,我发现自己希望能够从verifyInput中退出父函数。verifyInput通常给定一个prompt()函数。提示,有取消键。如果单击cancel,我想退出嵌套表达式。我该怎么做呢?

function verifyInput(foo, value){
    const input = foo();
    if (!isNaN(input) && !input || input === null || input === undefined){
        if(input === null){
            /*The input is null, because they hit the cancel button. I should exit myLoop here.*/
        } else {
            alert("Not valid.");
        }
        return verifyInput(foo,value);
    } else {
        if(value && input.search(value) < 0){
            alert("'"+[input]+"' is not a valid input.");
            return verifyInput(foo,value);
        }else{
            return input;
        }
    }
}
function myFunc(){
    var myInput = verifyInput( () => prompt("What is your input?"));
    alert(myInput);
    return myFunc();
}
myFunc();

没有办法直接从verifyInput停止调用者(myLoop)的执行,除非抛出异常。

正如其他人所说,您可以检查myLoop的返回值以有条件地停止它。

但也许一个更干净的解决方案是使用回调,它只会在输入不是"exit"时被调用。如果输入有效,这个回调将负责获取输入,并再次调用myFunc以继续循环。例子:

function verifyInput(prompter, callback) {
  var value = prompter()
  if (value === "exit") {
    return // don't proceed with the callback if `value` is "exit"
  }
  if (invalid(value)) { // function to be implemented
    alert("invalid")
    return verifyInput(prompter, callback)
  }
  callback(value)
}
function myFunc() {
  var prompter = () => prompt("What is your input?")
  verifyInput(prompter, (value) => {
    console.log(value) // logs the input
    myFunc()
  })
}
myFunc()

小提琴:https://jsfiddle.net/guisehn/r1Lwxkhp/