达到超时后调用另一个函数

时间:2018-05-07 09:13:48

标签: 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 个答案:

答案 0 :(得分:1)

第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绑定不清楚。

相关问题