title: How do I make a function wait until a database connection is established before continuing?
body: <p>Probably worded poorly, I understand async/promises/callbacks.</p>
  <p>What I'm trying to do is create a module which can be required (<code>database.js</code>), which I can then call methods such as <code>database.insert()</code> and <code>database.read()</code>.</p>
  <p>So here is my code:</p>
  <pre><code>require('dotenv').config()
  const {MongoClient} = require('mongodb');
  const client = new MongoClient(process.env.MONGO_URI);
  
  var db, queue;
  
  client.connect().then(e =&gt; {
      console.log('connected to database');
  
      db = client.db('filemanager');
      queue = db.collection('queue');
  });
  
  function insert (data, cb) {
      queue.insertOne(data)
          .then(res =&gt; {cb()})
  }
  
  module.exports = {
      insert: insert,
  }
  </code></pre>
  <p>The question is: How do I make it so when <code>database.insert()</code> is called, it will process instantly if db and queue are already defined, but if they aren't it will wait until they are, then will continue processing like normal?</p>