From 0a2da7115116fae133f8242965dcc58cc95549ff Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Wed, 12 Feb 2025 15:19:06 -0500 Subject: [PATCH] refactor: dedupe waitForConnectPromise logic --- lib/connection.js | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/lib/connection.js b/lib/connection.js index d9a12144f8..9c75df9739 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -830,17 +830,18 @@ Connection.prototype._waitForConnect = async function _waitForConnect(noTimeout) let timedOut = false; // The element that this function pushes onto `_queue`, stored to make it easy to remove later const queueElement = {}; + + // Mongoose executes all elements in `_queue` when initial connection succeeds in `onOpen()`. + const waitForConnectPromise = new Promise(resolve => { + queueElement.fn = resolve; + this._queue.push(queueElement); + }); + if (noTimeout) { - await new Promise(resolve => { - queueElement.fn = resolve; - this._queue.push(queueElement); - }); + await waitForConnectPromise; } else { await Promise.race([ - new Promise(resolve => { - queueElement.fn = resolve; - this._queue.push(queueElement); - }), + waitForConnectPromise, new Promise(resolve => { timeout = setTimeout( () => {