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' ...)
?
Asked
Active
Viewed 592 times
1

zlatanski
- 815
- 1
- 8
- 13
-
Possible duplicate of [Trigger Promise when an event fires](https://stackoverflow.com/questions/29933088/trigger-promise-when-an-event-fires) – Sven Feb 10 '18 at 17:37
-
`await` does not make much sense in the context of TCP sockets. What are you awaiting? A single message? An then? – Tomalak Feb 10 '18 at 17:43
1 Answers
4
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);
});

Michał Perłakowski
- 88,409
- 26
- 156
- 177