Perform a callback (obj) if the callback exists.

What I'm trying to do is make the callback parameter of the function optional. If the callback is passed, send the value to the callback function just to return the value. If I omit the callback, I return undefined.

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'); } ) } 
+7
javascript callback
source share
1 answer

You can simply check the following:

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

NOTE. Make sure you really use cb to call the callback function, not callback ;)

+16
source share

All Articles