ant_iw3r
ant_iw3r

Reputation: 222

Execute Callback(obj) if callback Exists Else return object

What I'm trying to do is make the callback parameter to a function optional. If a callback is passed send the value to the callback function else simply return the value. If I omit the callback I get undefined returned.

getByUsername = function(user_name, cb){
    async.waterfall([
        //Acquire SQL connection from pool
        function(callback){
            sql_pool.acquire(function(err, connection){
                callback(err, connection);
            });
        },
        //Verify credentials against database
        function(connection, callback){
            var sql = 'SELECT * FROM ?? WHERE ?? = ?';
            var inserts = ['users','user_name', user_name];
            sql = mysql.format(sql,inserts);
            connection.query(sql, function(err, results) {
                sql_pool.release(connection);
                callback(err, results);   
            });
        },
        //Create user object
        function(results, callback) {
            if(results.length < 1){
                if(cb){
                    cb(null);
                } else {
                    return null;
                }
            }else {
                var thisUser = new User(results[0]);
                if(cb){
                    cb(thisUser);
                } else {
                    return thisUser;
                }
            }
        }], function (err, results) {
            throw new Error('errrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrroooooorrrrrrrr');
        }
    )
}

Upvotes: 13

Views: 16060

Answers (1)

Floremin
Floremin

Reputation: 4089

You could just check like this:

if(cb && typeof cb === "function") {
    cb(num + 1);
}

NOTE: Make sure you're actually using cb to call your callback function and not callback ;)

Upvotes: 32

Related Questions