【发布时间】:2021-02-06 03:47:17
【问题描述】:
我正在尝试实现一些在打字稿中似乎不可能的事情,因为它是异步的。
我基本上有一个 net.Socket 对象通过 TCP 协议与服务器通信。
这是我想要实现的目标:
import * as net from 'net'
class TCPClient {
// The member used to communicate with the server
client: net.Socket;
[...]
/**
* Method called in another portion of code.
* In this method, I call client.write to send data to server.
* As first param, I put the command. As second param, a callback that is called when the
* data is sent.
* I listen then to the 'data' event to read the response from the server.
* I store the response into a variable. I return the variable.
* PROBLEM: Due to the asyncronous type of NodeJS, the variable appears as empty.
**/
command(cmd: string): string{
var res : string;
this.client.write(cmd, () => {
this.client.on('data', response => {
res = response.toString();
});
});
return res;
}
[...]
}
【问题讨论】:
-
您不能以任何语言同步返回异步结果(打字稿不具有异步性质)
标签: javascript node.js tcp promise return-type