简体   繁体   中英

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, eg

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 ...

If what you are confused by is how to put optionnal 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 conditionnal execution
                db.authenticate(user, pswd, () => {
                    callback();
                });
            } else {
                // Skip to the next step
                callback();
            }
        },
        (callback) => {
            // Whatever happenned in the previous function, we get here and can call the db
            db.collection.find();
        }
    ]);
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM