typescript - 如何在打字稿的循环中运行异步函数?
问题描述
如果我有这个
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
不会返回任何值,因此它可以是无效的。
我怎样才能做到这一点?
解决方案
这是一个带有一些助手的代码,可让您执行此操作
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
}
}
推荐阅读
- javascript - 单击锚点后如何关闭汉堡菜单
- python - OOP 设计问题 - 'postulantet' 对象没有属性 'tabla_postulante'
- python - 如何将表名格式化为 SQLite CREATE TABLE?
- admob - 我可以给用户奖励视频积分吗
- php - 如果用户从购物车中删除商品,如何运行功能?
- c# - 为什么我看不到将菜单项添加到菜单条的文本框
- javascript - 在浏览器上显示自定义的 Power Point 幻灯片
- nginx - 当通过 HTTP 路由到后端时,Nginx Ingress 如何处理通过 HTTPS (wss:...) 传入的 WebSocket 连接?(ws:...)?
- php - 如何在 Ajax 请求中重定向回 Laravel 8 中的错误
- android - 使用 FileProvider 共享缓存文件而不附加文件