Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
        }
    )
}
like image 317
ant_iw3r Avatar asked Jan 09 '14 01:01

ant_iw3r


People also ask

Does callback function have return statement?

No, callback should not be used with return.

How do you execute a callback?

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.

How do you return a response from an asynchronous call?

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.

Is callback and return same?

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.


1 Answers

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 ;)

like image 100
Floremin Avatar answered Oct 19 '22 18:10

Floremin