简体   繁体   中英

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. Is there version of this that return Promise so can be used with async/await ? Or should I use some third-party library for this or roll my own wrapper for 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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