Reputation: 845
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' ...)
?
Upvotes: 1
Views: 681
Reputation: 92639
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);
});
Upvotes: 4