I’ve tried to make a Node.js program to connect to a series of TCP sockets using promises.
The primary goal behind this was just a silly test: send a message, and wait for the socket to timeout or cause a connection error.
I then faced some inconsistent behavior of the program and have been trying to strip the code of any possible interference, until I got this snippet, which causes the problem:
const net = require('node:net');
function handshake (peer, socket) {
return new Promise ((resolve, reject) => {
socket.setTimeout(3000);
socket.on('timeout', () => (socket.destroy(), reject('timeout')));
socket.on('error', reject);
socket.connect(peer.port, peer.ip, () => socket.write('Hi'));
});
};
(async function () {
// 'peer_list' is an array with 200 objects in this shape:
// { ip:<string>, port:<number> }
const peer_list = require('./peer-list.json');
let promises = [];
for (let peer of peer_list)
promises.push(
handshake(peer, new net.Socket())
);
console.time('Timer');
const result = await Promise.allSettled(promises);
console.timeEnd('Timer');
})();
Some explanation: the data in “peer-list.json” is simply an array of objects in the shown format.
The IP addresses on them are either IPv6 or IPv4, and randomly generated. There is a copy of the file in: https://dontpad.com/5aUCGD9H74060377SUW4OzWPP3Du9PXAarnhse
Some more explanation: I know the promise in handshake
function is never fulfilled, only rejected, but that’s part of the thing, it is expected that the socket times out (even in the case the address exists and responds).
The expected output is just the time needed to resolve all the promises, printed by console.timeEnd
. But it simply doesen’t work sometimes: the program ends, but nothing is printed.
Out of 100 executions, only 40 had any output.
This means the console.timeEnd
is sometimes not being executed, and the program ends without finishing the Promise.allSettled
part.
I am running NodeJS v21.6.2, and Windows 10 v22H2, in a machine with 16GB of RAM and an Intel I5-10400F CPU. The task manager shows that the program never goes higher than 10Mb on memory usage and 0.2% on CPU usage. (I’m running it on VSCode terminal, but the same happened in CMD).
I know it doesn’t show much, but thats the output from running the program 10 times in a row:
(All of them finished execution in around the same timeframe: ~3-5s, but only 4 had output)
I also noticed a change when using different values for the timeout in socket.setTimeout(3000)
: when using a smaller value (100 to 400) it worked almost 90% of the time. But I noticed no changes when using a higher value (up to 10000).
So, in conclusion, why does it simply quit without finishing execution sometimes?