如何触发提前退出外部功能?

时间:2017-04-13 22:05:44

标签: javascript

我正在尝试创建一个函数,负责检查布尔值并提前退出并发出警告,如果为true。

这是我想要实现的例子:

function warnAndDie(shouldDie) {
    if(shouldDie) {
        console.log("go away, i'm dying!");
        // TODO: some code to cause the calling function to exit early
    }
}

function triggerTheWarnAndDie() {
    shouldWarnAndDie(true);
    console.log("I should never run!");
}

function dontTriggerTheWarnAndDie() {
    shouldWarnAndDie(false);
    console.log("I should run!");
}

我能做些什么才能使warnAndDie能够使调用函数提前终止?

谢谢

4 个答案:

答案 0 :(得分:3)

您有几种选择。我将为您列出两个非常基本的:

  1. 返回一个值(可能是布尔值)并根据初始返回值从调用者返回

    function shouldWarnAndDie(shouldDie) {
        if(shouldDie) {
            console.log("go away, i'm dying!");
            return true;
        }
        return false;
    }
    
    function triggerTheWarnAndDie() {
        var hasDied = shouldWarnAndDie(true);
        if (hasDied) return;
        console.log("I should never run!");
    }
    
  2. 抛出异常

    function shouldWarnAndDie(shouldDie) {
        if(shouldDie) {
            throw "Go away, i'm dying!";
            // or cleaner:
            // throw new dyingException("Go away, i'm dying!");
        }
    }
    
    function triggerTheWarnAndDie() {
       try {
          shouldWarnAndDie(true);
          console.log("I should never run!");
       }
       catch(err) {
          console.log(err+" He's dead Jim!");
       }
    }
    
  3. 现在有更多的高级机制可能超出你的范围,但关于回调和承诺的LINQ's nice answer绝对值得一看。

答案 1 :(得分:2)

这可以通过基本exception处理来实现。在这里,我创建了一个自定义异常,可以使用try catch语句捕获。

function shouldWarnAndDie(shouldDie) {
    if(shouldDie) {
        throw new DyingException();
    }
}

function triggerTheWarnAndDie() {
    try {
        shouldWarnAndDie(true);
    } catch(err) {
        console.log(err.message);
        return;
    }
    console.log("I should never run!");
}

function dontTriggerTheWarnAndDie() {
    try {
        shouldWarnAndDie(false);
    } catch(err) {
        console.log(err.message);
        return;
    }
    console.log("I should run!");
}

// custom Exception handler
function DyingException() {
    // do some custom exception handling here
    return new Error("Go away, I am dying!");
}

triggerTheWarnAndDie();     // Go away, I am dying!
dontTriggerTheWarnAndDie(); // I should run!

这是JsFiddle Example

答案 2 :(得分:0)

使用

return;

要退出的关键字

*这只是一个快速的解决方法。您可能希望查看错误检查和异常......

答案 3 :(得分:0)

我建议使用promises,但在所有浏览器中都不支持它。我们可以使用回调,其中回调内的代码仅在warnAndDie允许执行时执行。

function warnAndDie(shouldDie, fn) {
    if(shouldDie) {
        console.log("go away, i'm dying!");
        // TODO: some code to cause the calling function to exit early
        return;
    }
    fn();
}

function triggerTheWarnAndDie() {
    shouldWarnAndDie(true, function () {
        console.log("I should never run!");
    } );
}

function dontTriggerTheWarnAndDie() {
    shouldWarnAndDie(false, function () {
       console.log("I should run!");
    } );
}
相关问题