promise-based version of net.createServer

626 views Asked by At

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' ...) ?

1

There are 1 answers

0
Michał Perłakowski On BEST ANSWER

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);
  });