0

如何根据子函数的结果破坏父函数,以作为检查所有内容的一种方式,以防子函数出现问题?我目前有以下内容:

function Parent() { 
  Step1();
  Step2();
  Step3(); 
}

例如,如果子函数“Step1()”没有完成,我想打破父函数。

我想我可以创建一个全局变量作为标志,并结合父函数中的 if 语句,这样如果标志在子函数中从“真”变为“假” 整个函数就会中断,但是这个没有工作给出错误说“休息是非法的”。这是我尝试过的:

var flag = "true" // Global variable

function Parent() { 
  Step1(); //Within this child function, I have an "if" condition that sets flag "true"/"false" depending on the outcome

     if (flag == "false") { //I was hoping this would read the incoming flag and trigger a break, if the flag was set to "false" in Step1();
     }

  Step2();

  Step3(); 
}

现在,即使 Step1() 不正确,我的脚本也会遍历所有子函数,并且无法停止此序列,我只会不断地从父函数中得到不希望的结果。

我还认为如果我使用“break;” 在整个 .gs 文件中的任何时候,它都会破坏整个事情,但事实并非如此。如果我自己运行 Step1()并且“if”条件激活“break;” 它成功中断,但是当我运行父函数时,它只是继续进入下一个函数。

谢谢,内斯特

4

2 回答 2

0

应用打击逻辑

   let flag = true;
    function(){
        if (flag == "false") { 
            "false" in child1();
            goto lineContinue
         }

     child2();
     child3();

    }

    lineContinue: child4();
于 2020-03-02T08:44:19.597 回答
0

要成功破解,请添加一个return

return 语句结束函数执行

if (flag == "false") { return; }

或者,您可能会throw出错或玩弄try...catch

实时片段:

let flag = 0;
function main() {
  console.info("main1");
  function step1() {
    console.info('step1');
    flag = 1;
  }
  function step2() {
    console.info('step2');
  }
  step1();
  if (flag) return; //stops execution
  step2();
}

function main2() {
  console.info("main2");
  function step1() {
    console.info('step1');
  }
  function step2() {
    console.info('step2');
    throw new Error('Step 2 fatal error');
  }
  function step3() {
    console.info('step3');
  }
  try {
    step1();
    step2();
    step3();
  } catch (e) {
    console.error(e.message);
  }
}
main();
main2();

于 2020-03-02T09:15:05.187 回答