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');
}
)
}
No, callback should not be used with return.
A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. console.
The A in Ajax stands for asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $. ajax returns immediately and the next statement, return result; , is executed before the function you passed as success callback was even called.
Return statements are used to indicates the end of a given function's execution whereas callbacks are used to indicate the desired end of a given function's execution.
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
;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With