【问题标题】:setTimeout not working in try/catchsetTimeout 在 try/catch 中不起作用
【发布时间】:2018-03-08 23:17:35
【问题描述】:

我正在等待提供商更新this.myprovider.SomeVarIsNotUndefined。我不能使用 Promise 让我的脚本等待,所以我想出了这个,但它似乎只运行一次。所以当this.myprovider.SomeVarIsNotUndefined = undefined 时setTimeout() 不会在catch 区域重新触发,即使console.log(err) 正在触发。

someFunction(){

  try {

      if(this.myprovider.SomeVarIsNotUndefined){
        //...
         console.log("works");
      }
  }
  catch(err) {

    //if error then re-run after 0.5 seconds
    setTimeout(() => {  this.someFunction(); }, 500);
     console.log(err);

  }

}

//run func for the first time
this.someFunction();

【问题讨论】:

  • 它按预期工作,但如果 this.myprovider.SomeVarIsNotUndefined 没有定义,这将是一个无限循环,它将继续每 500 毫秒调用一次自己
  • 可能有更好的方法来解决这个问题,但话虽如此,您为什么不检查if(this.myprovider.SomeVarIsNotUndefined === undefined) 而不是尝试提示异常?
  • 即使我尝试了您的代码,它也能按您的预期完美运行
  • 您的代码按预期工作。如果您可以发布有问题的实际代码会有所帮助。
  • 我发现因为我使用的是 if myarray.length 它不起作用但它是一个字符串/数字所以我只是在函数末尾添加了一个变量来完成承诺

标签: javascript node.js angular ionic-framework


【解决方案1】:

下面的代码工作得非常好,这是第一次未定义变量,程序流到了 catch 块。然后在catch块中,我定义了变量然后设置超时函数重新触发函数并给出console.log - “works”

<script>

function someFunction(){
  try {

      if(SomeVarIsNotUndefined){
        //...
         console.log("works");
      }
  }
  catch(err) {

    //if error then re-run after 0.5 seconds
    setTimeout(() => {  SomeVarIsNotUndefined = 1; this.someFunction(); }, 500);
     console.log(err);

  }

}

//run func for the first time
this.someFunction();
</script>

https://www.w3schools.com/code/tryit.asp?filename=FP6TDP0ESYVW

【讨论】:

  • 我发现因为我使用的是 if myarray.length 它不起作用但它是一个字符串/数字所以我只是在函数末尾添加了一个变量来完成承诺
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-06
  • 1970-01-01
相关资源
最近更新 更多