0

The below code attempts to connect to a MongoDB instance.

When connected successfully it prints, closes the connection and thus terminates as expected.

However, when the connection is not successful (e.g. the MongoDB instance is not running) the below code fails to terminate even though the client variable is undefined.

What I can do to allow it to terminate in the case of a failed connection? Repro below.

Per this post (my nodejs script is not exiting on its own after successful execution) I tried running process._getActiveRequests() and process._getActiveHandles() to see what was active and thus preventing node.js from exiting. Those show that there are indeed active requests/handles but I am not sure how to close them.

const MongoClient = require('mongodb').MongoClient;

async function main(){
  let client;
  try {
    client = await MongoClient.connect('mongodb://localhost:27017');
    console.log('Connected successfully!');
  } catch (error) {
    console.log(`Failed to connect:${error}`);
  } finally {
    if (client)
      client.close();
  }
}

main();
sivano
  • 619
  • 1
  • 6
  • 12
  • 1
    What happens if you take the 'if (client)' out of the finally statement? – Nick May 10 '19 at 03:26
  • client is undefined when the connection isn't successful, and so without the if() clause, .close() is called on undefined, which throws an exception (UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'close' of undefined) but even then the process does not terminate. – sivano May 11 '19 at 04:40

0 Answers0