javascript 如果回调存在则执行回调(obj)否则返回对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21010143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:49:11  来源:igfitidea点击:

Execute Callback(obj) if callback Exists Else return object

javascriptcallback

提问by ant_iw3r

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.

我想要做的是使回调参数成为可选的函数。如果传递了回调,则将值发送到回调函数,否则只需返回该值。如果我省略回调,我会返回 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');
        }
    )
}

回答by Floremin

You could just check like this:

你可以这样检查:

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

NOTE: Make sure you're actually using cbto call your callback function and not callback;)

注意:确保您实际上是cb用来调用回调函数而不是callback;)