首页 > 解决方案 > 如何在打字稿的循环中运行异步函数?

问题描述

如果我有这个

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再次运行,在无限循环中,但使用setTimeout. 也Run不会返回任何值,因此它可以是无效的。

我怎样才能做到这一点?

标签: typescriptasync-await

解决方案


这是一个带有一些助手的代码,可让您执行此操作

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
    }
    
}

推荐阅读