无法在setInterval函数内调用异步函数

时间:2017-10-18 14:24:14

标签: javascript typescript setinterval

我想调用从setInterval函数内的服务类实例调用的异步函数。

        class async {

        constructor(public service: Service){}            

            async doSomeAsyncTask(){

               setInterval(await this.service.anotherAsyncTaskInTheServiceClass(),3000); 

       //want to call the inside of setInterval function repeatedly in every 3ms.       
      } 
    }
  }

2 个答案:

答案 0 :(得分:4)

setInterval期望第一个参数是一个函数,所以我认为它应该是

setInterval(async () => { await this.service.anotherAsyncTaskInTheServiceClass() },3000); 

*感谢您更正@Evariste *

答案 1 :(得分:0)

请务必在try / catch中将所有可能引发异常的操作包装到setInterval / setTimer的异步函数中,以免发生未处理的异常,请参见Async, Promises, and Timers in Node.js

相关问题