Skip to content

Commit

Permalink
refactor: dedupe waitForConnectPromise logic
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Feb 12, 2025
1 parent 9159ced commit 0a2da71
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
() => {
Expand Down

0 comments on commit 0a2da71

Please sign in to comment.