diff --git a/src/mongo_client.ts b/src/mongo_client.ts index d7779aeb47..8e56c4f7ae 100644 --- a/src/mongo_client.ts +++ b/src/mongo_client.ts @@ -504,10 +504,14 @@ export class MongoClient extends TypedEventEmitter { return; } + // clear out references to old topology + const topology = this.topology; + this.topology = undefined; + // If we would attempt to select a server and get nothing back we short circuit // to avoid the server selection timeout. const selector = readPreferenceServerSelector(ReadPreference.primaryPreferred); - const topologyDescription = this.topology.description; + const topologyDescription = topology.description; const serverDescriptions = Array.from(topologyDescription.servers.values()); const servers = selector(topologyDescription, serverDescriptions); if (servers.length !== 0) { @@ -522,10 +526,6 @@ export class MongoClient extends TypedEventEmitter { } } - // clear out references to old topology - const topology = this.topology; - this.topology = undefined; - await new Promise((resolve, reject) => { topology.close({ force }, error => { if (error) return reject(error); diff --git a/test/integration/node-specific/mongo_client.test.ts b/test/integration/node-specific/mongo_client.test.ts index f92ccee05a..2955e41293 100644 --- a/test/integration/node-specific/mongo_client.test.ts +++ b/test/integration/node-specific/mongo_client.test.ts @@ -385,6 +385,14 @@ describe('class MongoClient', function () { } }); + it('can call close() concurrently', async function () { + const client = this.configuration.newClient(); + await client.connect(); + // Ensure topology is opened before trying to close + await client.db().command({ hello: 1 }); + await Promise.all([client.close(), client.close()]); + }); + context('explict #connect()', () => { let client: MongoClient; beforeEach(function () {