如何在typescript中的循环中运行异步函数?
如果我有这个如何在typescript中的循环中运行异步函数?,typescript,async-await,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
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
}
}
class-Foo{
建造师(obj:编号){
//跑“跑”
//每次完成后1秒钟后运行“run”
}
专用异步运行(obj:number):承诺{
//有些代码确实在等待使用
}
}
创建实例时,我希望它运行run
,完成后等待1秒,然后在无限循环中再次运行run
,但使用setTimeout
。此外,运行
不会返回任何值,因此它可能是无效的
我怎样才能做到这一点呢?下面是一段代码,其中有一些帮助程序可以帮助您做到这一点
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
}
}
class-Foo{
建造师(obj:编号){
这是一种新方法;
}
专用异步startRunning():承诺{
for(设i=0;i++){
等着吧,跑(我);
等待这个。延迟(1000);
}
}
专用延迟(超时:数字):承诺{
返回新承诺(res=>setTimeout(res,timeout));
}
专用异步运行(obj:number):承诺{
//有些代码确实在等待使用
}
}
while(true){await delay(1000);…}
构造函数不应该启动异步进程。如果我超过了最大整数怎么办?嗯,它不会Number.MAX\u SAFE\u INTEGER
是超长的。在你们等待这么多滴答声之前,地球将被毁灭