From 25097cd63209fbf73b22a340a70e055c9567a937 Mon Sep 17 00:00:00 2001 From: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com> Date: Sat, 18 Mar 2023 16:36:19 -0700 Subject: [node:net] Fix issue with `listen` callback firing before it's listening --- src/bun.js/net.exports.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/bun.js/net.exports.js b/src/bun.js/net.exports.js index 9119f525c..423aae362 100644 --- a/src/bun.js/net.exports.js +++ b/src/bun.js/net.exports.js @@ -57,6 +57,7 @@ const { Bun, createFIFO, Object } = import.meta.primordials; const { connect: bunConnect } = Bun; const { Duplex } = import.meta.require("node:stream"); const { EventEmitter } = import.meta.require("node:events"); +var { setTimeout } = globalThis; const bunTlsSymbol = Symbol.for("::buntls::"); const bunSocketServerHandlers = Symbol.for("::bunsocket_serverhandlers::"); @@ -633,7 +634,15 @@ class Server extends EventEmitter { this.#server.data = this; this.#listening = true; - process.nextTick(emitListeningNextTick, this, onListen); + + // We must schedule the emitListeningNextTick() only after the next run of + // the event loop's IO queue. Otherwise, the server may not actually be listening + // when the 'listening' event is emitted. + // + // That leads to all sorts of confusion. + // + // process.nextTick() is not sufficient because it will run before the IO queue. + setTimeout(emitListeningNextTick, 1, this, onListen); } catch (err) { this.#listening = false; process.nextTick(emitErrorNextTick, this, err); -- cgit v1.2.3