title: Node.js Async/Await module export
body: <p>I'm kinda new to module creation and was wondering about module.exports and waiting for async functions (like a mongo connect function for example) to complete and exporting the result. The variables get properly defined using async/await in the module, but when trying to log them by requiring the module, they show up as undefined. If someone could point me in the right direction, that'd be great. Here's the code I've got so far:</p>
  
  <pre><code>// module.js
  
  const MongoClient = require('mongodb').MongoClient
  const mongo_host = '127.0.0.1'
  const mongo_db = 'test'
  const mongo_port = '27017';
  
  (async module =&gt; {
  
    var client, db
    var url = `mongodb://${mongo_host}:${mongo_port}/${mongo_db}`
  
    try {
      // Use connect method to connect to the Server
      client = await MongoClient.connect(url, {
        useNewUrlParser: true
      })
  
      db = client.db(mongo_db)
    } catch (err) {
      console.error(err)
    } finally {
      // Exporting mongo just to test things
      console.log(client) // Just to test things I tried logging the client here and it works. It doesn't show 'undefined' like test.js does when trying to console.log it from there
      module.exports = {
        client,
        db
      }
    }
  })(module)
  </code></pre>
  
  <p>And here's the js that requires the module</p>
  
  <pre><code>// test.js
  
  const {client} = require('./module')
  
  console.log(client) // Logs 'undefined'
  </code></pre>
  
  <p>I'm fairly familiar with js and am still actively learning and looking into things like async/await and like features, but yeah... I can't really figure that one out</p>