【问题标题】:Javascript Exit from child functionJavascript退出子函数
【发布时间】:2013-06-06 14:50:46
【问题描述】:

我有一组绑定,它们在代码之前和之后在函数内部触发。如下:

function global() {
    before(); // call all before binds here

    //... mainFunction code...

    after(); // call all after binds here 
}

如果before(); 回调中的某个函数想要退出或停止global() 进一步运行,我如何在不检查返回值的情况下停止它?

【问题讨论】:

    标签: javascript function parent


    【解决方案1】:

    在不检查值returned 的情况下实现此目的的唯一方法是通过throwing 和error 引发异常。

    function before() {
        throw new Error('Ending execution');
    }
    function after() {
        console.log('Have you met Ted?');
    }
    function global() {
        before();
        // never reaches here
        after();
    }
    global(); // Error: Ending execution
    console.log('foo'); // not executed
    

    如果您在某处调用了global,并希望在调用之后的任何代码继续执行,则需要用try..catch 包装它,例如

    function global() {
        try {
            before();
            // never reaches here
            after();
        } catch (e) {
            console.log(e); // log error. Leave this block empty for no action
        }
    }
    global(); // Error logged
    console.log('bar'); // still executed
    

    【讨论】:

    • 这不会也停止其他功能吗?来自 ouside global() 的其他函数;
    • 其他系列的功能,是的。我会编辑解决这个问题
    • @Basit 进一步,我在复制您的示例时使用了 global,但是如果您实际上将名为 global 的东西放在全局命名空间中,您可能会遇到冲突问题,因此请尝试选择不同的名称/编写模块化代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多