如何在TS中的类方法内声明SetTimeout()并将另一个类方法用作回调?

时间:2019-04-28 08:19:26

标签: javascript typescript callback settimeout

我想使用方法Reconnection()作为SetTimeout()中的回调,而不是类之外的Reconnection()函数。我已经尝试声明this作为引用并使用=>,但是没有成功。 呼叫时:

setTimeout(this.Reconnection, CONFIG.ENTCS_ReconnectionTimer);

我得到:

  

TypeError [ERR_INVALID_CALLBACK]:回调必须是一个函数”

这是我的代码:

 export class CommTcp {

    constructor(receivedHost: string, receivedPort: number) {
       ...
    }

    //Connect socket and register listeners to socket events
    public StartClient() {
       ...
    }
    .
    .
    .

    //Handle connection closed -> Start timer for reconnection
    HandleClose() {
        console.log('CommTcp. Client closed');
        setTimeout(this.Reconnection, CONFIG.ENTCS_ReconnectionTimer);
    }

     //what i want - Not working!!!
    Reconnection() {
        console.log(`CommTcp. Try to reconnect`);
        this.StartClient();
    }
}

当我在类外声明函数并将调用更改为:

setTimeout(Reconnection, CONFIG.ENTCS_ReconnectionTimer); //in the class

//Callback function outside the class for handling socket reconnection 
function Reconnection() {
    let myNewTcp = new CommTcp(CONFIG.ENTCS_IP, CONFIG.ENTCS_PORT);
    myNewTcp.StartClient();
}

它可以工作,但不是我想要的

谢谢, 志美

0 个答案:

没有答案