首页 > 解决方案 > 达到超时后调用另一个函数

问题描述

我在 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);
});              
}

标签: typescript

解决方案


第 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您的示例中的绑定不清楚。


推荐阅读