title: Node.JS waiting for variable to be set
body: <p>What I'm trying to do is to allow the sort_order to be specified or left blank.
  When it's specified, it's used.
  When it's not specified, the database is queried for the highest number, which is incremented and used.
  My issue is that the database call is Async and inside the "if" statement.</p>
  
  <p>What's the best practice for ensuring that "sort_order" is not undefined before inserting new data to the database?</p>
  
  <p>A snippet of code is shown below:</p>
  
  <pre><code>  if (sort_order == undefined) {
      MongoClient.connect(dbUrl, function (err, db) {
        var dbo = db.db("HIDDEN");
  
        dbo.collection("HIDDEN").findOne({}, {"sort": { sort_order: -1 } }, function (err, data) {
          sort_order = data.sort_order + 1;
        });
  
      });
    }
  
    console.log(sort_order);
  </code></pre>
  
  <p>Thanks in advance,</p>
  
  <p>James</p>
  
  <p><em>EDIT (08/06/2018): I believe that this question differs from the other one suggested because there is the case when sort_order is not undefined and can be previously specified. Using the other question's answers, duplicate could would have to be written (inside the callback inside the if statement and after the if statement)</em></p>