Andy Brunner
Andy Brunner

Reputation: 173

Node.js How to do conditional Callback?

I am still struggling with the nested callback structure of Node.js. I have looked as async, co and other methods, but they do not seem to help.

What is the best practice on how to code, e.g.

var db = MongoClient.connect(url, callback1 () {
   if (auth) }
      db.authenticate(user, pswd, callback2 () {
      --- should continue with db.collection.find (authenticated)
   )
   --- should continue with db.collection.find (non-authenticated)
}

So the question ist: How should I code this sequence to be able to execute the db calls following db.connect or db.authenticate (and both callbacks are completed)? The only way I can think of is to have the following db-calls in a separate function and call this function in both callback routines. Not really elegant ...

Upvotes: 0

Views: 782

Answers (2)

DrakaSAN
DrakaSAN

Reputation: 7873

If what you are confused by is how to put optional conditions before a callback, using async you can do:

var async = require('async');

var db = MongoClient.connect(url, () => {
    async.series([
        (callback) => {
            //Branching
            if(auth) {
                // Do conditional execution
                db.authenticate(user, pswd, () => {
                    callback();
                });
            } else {
                // Skip to the next step
                callback();
            }
        },
        (callback) => {
            // Whatever happened in the previous function, we get here and can call the db
            db.collection.find();
        }
    ]);
});

Upvotes: 1

Hitmands
Hitmands

Reputation: 14199

I'm not sure that I fully understand what you are asking, by the way, if you want to run a callback depending on some conditions (eg: requires or not authentication)... you can use promises:

var db = MongoClient.connect(url, callback1 () {
   if (auth) }
      db.authenticate(user, pswd, callback2 () {
      --- should continue with db.collection.find (authenticated)
   )
   --- should continue with db.collection.find (non-authenticated)
}

var MongoClientConnect = (url, username, password) => new Promise((resolve, reject) => {
  
  var db = MongoClient
    .connect(url, () => {
      if(!requiresAuthentication) {
        return resolve(db);    
      }
  
      db.authenticate(username, password, () => {
        //check if login success and
        resolve(db);
      });
    })
  ;
});

// THEN
MongoClientConnect()
  .then(db => db.collection.find("bla bla bla"))
;

Upvotes: 0

Related Questions