如何在TypeScript循环中运行异步函数?

时间:2020-07-26 20:57:02

标签: typescript async-await

如果我有这个

class Foo {
    constructor(obj:number) {
         // run "Run"
         // run "Run" after 1 second after each time it finishes
    }
    private async Run(obj:number):Promise<void> {
         // some code does uses await
    }
}

创建实例时,我希望它运行Run,完成后等待1秒钟,然后它无限循环地再次运行Run,但使用{{1} }。此外,setTimeout不返回任何值,因此它可以为空。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

这是带有一些帮助程序的代码,使您可以执行此操作

class Foo {
    constructor(obj:number) {
       this.startRunning();
    }
    private async startRunning():Promise<void> {
         for(let i = 0;; i++) {
            await this.Run(i);
            await this.delay(1000);
         }
    }
    private delay(timeout: number): Promise<void> {
      return new Promise(res => setTimeout(res, timeout));
    }
    private async Run(obj:number):Promise<void> {
         // some code does uses await
    }
    
}