我要做的是将callback参数设置为函数可选。如果传递回调,则将值发送给回调函数,否则只返回该值。如果我省略回调,则返回未定义。
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');
}
)
}
答案 0 :(得分:21)
您可以像这样检查:
if(cb && typeof cb === "function") {
cb(num + 1);
}
注意:请确保您实际上使用cb
来调用回调函数,而不是callback
;)