I’ve been working with TCP connections lately, which means that upon connection from the client, my server needs to create a bunch of event listeners for things like .on(‘data’, and .on(‘timeout’
I also need to go through some logic to determine what I should do after connection, but before data or timeout. In my first pass, I created the event listeners towards the bottom of the .on(‘connection’ function.
That worked great until I started using return statements to change the flow inside of the .on(‘connection’ function. Once I did that, I started running into issues because the return statement resulted in the event listeners never being declared.
The lesson there for me is that I’m nearly always going to be best off setting up an event listener earlier rather than later. A niaeve concern might be that the on data listener will fire off before you get to the rest of your on connect function, but all the on data listener does is let stuff be placed on the event table, and then eventually be moved down to the event queue.
Nothing will be pulled off of the event queue though until the current function has finished running. So, you’re generally going to be just fine…unless maybe your current function is an async/await function, in which case it is possible that you’ll set up the event listeners, and then shift the function to the event table, allowing the on data listeners to fire off and get pulled onto the call stack before the original function resolves its asynchronous call and is placed back on the call stack.
Layers inside of layers, so my revised rule of thumb is to place any event listeners right after my await call. I hope that is helpful!