Javascript setTimeout在try/catch中不工作

Javascript setTimeout在try/catch中不工作,javascript,node.js,angular,ionic-framework,Javascript,Node.js,Angular,Ionic Framework,我正在等待提供程序更新this.myprovider.somevarisnoundefined。我不能用承诺让我的脚本等待,所以我想出了这个,但它似乎只运行一次。因此,当this.myprovider.someVarisNotDefined=未定义时,setTimeout()不会在catch区域重新触发,即使触发了console.log(err) someFunction(){ try { if(this.myprovider.SomeVarIsNotUndefined){

我正在等待提供程序更新
this.myprovider.somevarisnoundefined
。我不能用承诺让我的脚本等待,所以我想出了这个,但它似乎只运行一次。因此,当
this.myprovider.someVarisNotDefined
=
未定义时,
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();

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


函数someFunction(){
试一试{
如果(某些变量未定义){
//...
控制台日志(“工作”);
}
}
捕捉(错误){
//如果出现错误,则在0.5秒后重新运行
setTimeout(()=>{someVarisNotDefined=1;this.someFunction();},500);
控制台日志(err);
}
}
//第一次运行func
this.someFunction();

其工作如预期,但如果this.myprovider.SomeVarIsNotUndefined未定义,则这将是一个无限循环。它将每隔500分钟继续调用自己。这可能是更好的方法,但既然如此,为什么不检查
if(this.myprovider.SomeVarIsNotUndefined==未定义)
而不是试图提示异常?即使我尝试了您的代码,它也能像您期望的那样完美地工作您的代码也能像您期望的那样工作。如果你可以发布有问题的实际代码,这会有所帮助。我发现,因为我使用的是If myarray.length,它不起作用,但它带有字符串/数字,所以我只是在函数末尾添加了一个变量来完成Promise。我发现,因为我使用的是If myarray.length,它不起作用,但它带有string/number,因此我只是在函数末尾添加了一个变量来完成承诺
<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>