return显示未定义的javascript

r6l8ljro  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(363)

我正在编写一个discord bot来检查数据库中的点,然后返回它们。这是我目前的密码。

function userCheck(id, name) {
        date = new Date().toISOString().slice(0, 19).replace('T', ' ');
        con.query("SELECT id FROM users WHERE id = "+id, function (err, row) {
            if (!(row && row.length) ) {
                    con.query("INSERT INTO `users` (id,name,rank,points,signup) VALUES ('"+id+"', "+name+", '0', '0' , '"+date+"')"), function (err, result, fields){
                        if (err) throw err;
                    }
            }else{
                //fine
            }
    });
    }

    function checkPoints(user){
        id = user.id;
        name = con.escape(user.username);

        userCheck(id, name);
        console.log("SELECT points FROM users WHERE id = "+id);
        con.query("SELECT points FROM users WHERE id = "+id, function (err, result, fields){
            return result[0].points;
        });
    }

我调用这些函数的代码如下: return message.author.send(checkPoints(message.author)); 这会导致discordjs错误,因为它试图返回空消息。这意味着我的功能没有恢复正常。我看了一遍又一遍这可能只是一个简单的修复,但我看不到它。
提前谢谢

vdgimpew

vdgimpew1#

function checkPoints(user){ 不返回任何内容,即返回未定义的内容
由于con.query是异步的,所以最简单的解决方法就是使用回调,如下所示

function checkPoints(user, cb){
    id = user.id;
    name = con.escape(user.username);

    userCheck(id, name);
    console.log("SELECT points FROM users WHERE id = "+id);
    con.query("SELECT points FROM users WHERE id = "+id, function (err, result, fields){
        cb(result[0].points);
    });
}

checkPoints(message.author, function(result) {
    message.author.send(result);
});

或者,用承诺

function checkPoints(user){
    return new Promise(function(resolve, reject) {
        id = user.id;
        name = con.escape(user.username);

        userCheck(id, name);
        console.log("SELECT points FROM users WHERE id = "+id);
        con.query("SELECT points FROM users WHERE id = "+id, function (err, result, fields){
            if(err) return reject(err);
            resolve(result[0].points);
        });
    });
}

checkPoints(message.author)
.then(function(result) {
    message.author.send(result);
});

相关问题