简体   繁体   English

基于承诺的net.createServer版本

[英]promise-based version of net.createServer

If I create TCP server with net.createServer , I can do conn.on('data' ...) in the connection handler with a callback. 如果我使用net.createServer创建TCP服务器, net.createServer可以在带有回调的连接处理程序中执行conn.on('data' ...) Is there version of this that return Promise so can be used with async/await ? 是否有返回Promise版本,因此可以与async/await一起使用? Or should I use some third-party library for this or roll my own wrapper for conn.on('data' ...) ? 还是我应该为此使用一些第三方库或为conn.on('data' ...)滚动自己的包装器?

conn.on('data' ...) can't be replaced with a promise, because it's an event listener, which means that the callback function can be called multiple times. conn.on('data' ...)不能用promise代替,因为它是一个事件侦听器,这意味着可以多次调用该回调函数。 A promise can't be resolved multiple times. 一个承诺不能多次解决。

If you're sure that the data event will be emitted only once, you can write a wrapper which will return a promise: 如果您确定data事件仅发出一次,则可以编写一个包装器,该包装器将返回一个Promise:

const onData = conn =>
  new Promise((resolve, reject) => {
    conn.on('data', resolve);
    conn.on('error', reject);
  });

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

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