简体   繁体   English

Promise... 返回类型而不是 Promise<Type>

[英]Promise... Return type instead of Promise<Type>

I'm trying to achieve something that seems impossible in typescript due to it's asynchronous nature.由于它的异步性质,我正在尝试实现在打字稿中似乎不可能的东西。

I basically have a net.Socket object to communicate with a server through TCP protocole.我基本上有一个 net.Socket 对象通过 TCP 协议与服务器通信。

Here is what I would like to achieve :这是我想要实现的目标:

 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; } [...] }

You have to make an asynchroneous method using Promises, something like:您必须使用 Promises 制作一个异步方法,例如:

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

But to make it simpler you may use async/await in your calling code.但为了更简单,您可以在调用代码中使用 async/await。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM