typescript - 达到超时后调用另一个函数
问题描述
我在 JavaScript 中有以下代码,我想将其转换为 TypeScript:
testJS(): void {
$timeout(function () {
this.done = true;
}, 1).then(function () {
$timeout(function () {
this.done = false;
}, 1000);
});
}
我正在尝试在 TypeScript 中使用 setTimeout 函数,但我不太确定如何解决“.then”部分。谁可以帮我这个事?到目前为止的代码:
testTS(): void {
setTimeout(function () {
this.done = true;
}, 1).then(function () {
setTimeout(function () {
this.done = false;
}, 1000);
});
}
解决方案
第 1 步:使用setTimeout
function wait(ms: number): Promise<void> {
return new Promise<void>(resolve => setTimeout(resolve, ms))
}
第 2 步:使用承诺
function testJS(): void {
wait(1).then(() => {
this.done = true;
return wait(1000)
}).then(() => {
this.done = false;
})
}
第 2 步(替代):await
承诺
async function testJS2(): Promise<void> {
await wait(1)
this.done = true;
await wait(1000)
this.done = false;
}
注意:this
您的示例中的绑定不清楚。
推荐阅读
- php - 在自定义 wp-query 中创建后置过滤器
- android - 从 EditText 中删除 maxLength 集
- javascript - ESLint 不会从 npm 命令抛出任何错误
- php - 加入结果不正确 php
- php - 雄辩模型的正确关系
- javascript - Create-React-App 在 WHM/cPanel 服务器上显示空白页面
- c - 康威的士兵 - C
- javascript - 如何在 .js 文件中的 app.post() 中定义函数
- php - login_check 302 找到 symfony 2
- sql-server - 强制访问忘记链接表的用户名和密码