1

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.

What's the best practice for ensuring that "sort_order" is not undefined before inserting new data to the database?

A snippet of code is shown below:

  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);

Thanks in advance,

James

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)

James B.
  • 571
  • 5
  • 17

1 Answers1

1

You should move from callbacks to Promises or Async/Await, the latter being a lot easier to read:

async function retrieveValue(sort_order) {
    if (sort_order === undefined) {
        const db = await MongoClient.connect(dbUrl);
        const dbo = db.db("HIDDEN");
        const data = await dbo.collection("HIDDEN").findOne({}, {"sort": { sort_order: -1 }});
        return data.sort_order + 1;
      };
    return sort_order;
  }

EDIT (With try-catch block):

 async function retrieveValue(sort_order) {
         try {
            if (sort_order === undefined) {
                const db = await MongoClient.connect(dbUrl);
                const dbo = db.db("HIDDEN");
                const data = await dbo.collection("HIDDEN").findOne({}, {"sort": { sort_order: -1 }});
                return data.sort_order + 1;
            }
         } catch (error) {
             console.log(error);
         }
    return sort_order;
  }

You basically mark the function as async when you define it, and whenever you are expecting a Promise, you mark it with await so that it 'waits' for your data.

andrralv
  • 810
  • 7
  • 18
  • Exactly what I was after! I always found the async/await concept confusing but this clears it up wonderfully. However, if there was an error returned on the "const data =..." line, how would you go about getting that? When using callbacks there are two parameters for err and data. – James B. Jun 08 '18 at 12:13
  • @JamesB. take a look at the edited answer, you can wrap it in a try-catch block to retrieve the error in the catch statement. – andrralv Jun 08 '18 at 18:20