diff options
author | 2023-03-18 16:36:19 -0700 | |
---|---|---|
committer | 2023-03-18 16:36:19 -0700 | |
commit | 25097cd63209fbf73b22a340a70e055c9567a937 (patch) | |
tree | 57ca10ffb0e42cae60f1f710989edf99fd0032ce | |
parent | d9711c64eb0bf4a9ebc232228c6d8ba0d9f495a6 (diff) | |
download | bun-25097cd63209fbf73b22a340a70e055c9567a937.tar.gz bun-25097cd63209fbf73b22a340a70e055c9567a937.tar.zst bun-25097cd63209fbf73b22a340a70e055c9567a937.zip |
[node:net] Fix issue with `listen` callback firing before it's listening
-rw-r--r-- | src/bun.js/net.exports.js | 11 |
1 files changed, 10 insertions, 1 deletions
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); |