node.jstimeres6-promise

Is this an inconsistent behavior with node.js promises?


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)

execution example

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?


Solution

  • Nodejs may automatically exit when the last of the sockets are done before your promise-based code gets to execute. I've seen this happen in some circumstances (as a side effect of how the event loop and resolved promises with resolve handlers to call aren't entirely aware of each other).

    You can test this hypothesis by adding a setTimeout(() => {}, 1000*60*60) which just makes sure your nodejs program doesn't exit until you tell it to (or until an hour passes). Then, to make your program exit as intended, add a process.exit() after your console.timeEnd('Timer');.

    What appears to be happening is that the last remaining socket gets an error and calls the reject handler you registered in your handshake() function. The way promise reject handlers work is they don't call the code attached to them until the event loop unwinds. But, when the event loop unwinds, the nodejs event loop code discovers that there's nothing left to keep it running (no open sockets or files or timers or other asynchronous resources) so it auto-exits. That event loop code that detects when its time to auto-exit appears to not be aware of promises that are waiting to call their resolve or reject handlers.