【问题标题】:Promise... Return type instead of Promise<Type>Promise... 返回类型而不是 Promise<Type>
【发布时间】: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


【解决方案1】:

你必须使用 Promises 来创建一个异步方法,比如:

command(cmd: string): Promise<string> {
  return new Promise((resolve) => {
    this.client.write(cmd, () => {
      this.client.on('data', response => {
        resolve(response.toString());
      });
    });
  })
}

但为了更简单,您可以在调用代码中使用 async/await。

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 2017-03-17
    • 2021-06-05
    • 2021-03-17
    • 2017-06-02
    • 1970-01-01
    • 2021-10-17
    • 2021-08-07
    • 1970-01-01
    相关资源
    最近更新 更多