我想要做的是使回調參數可選的功能。如果通過回調,則將值發送給回調函數,否則只返回值。如果我省略回調,則返回undefined。執行回調(OBJ)如果回調存在否則返回對象
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');
}
)
}
那麼,有什麼問題嗎? –
哈哈。抱歉。它不能正常工作。我沒有定義回調。 –
它應該有點顯而易見。看看參數的名稱。另外,如果它爲空則爲什麼要調用回調函數? –