discord.js/node/mysql :如何等到查询 returns 结果

discord.js/node/mysql : how to wait until query returns result

我目前正在尝试为多个 Discord 服务器编写一个机器人。 问题是,代码不等待数据库 return 结果。在当前情况下,我正在尝试检查消息的作者 ID 是否已在 mysql 数据库中。

我读了一些关于 async/await 的东西,但我需要你的帮助来理解如何 link 这些东西在一起!

const Discord = require('discord.js');
var mysql = require('mysql');
// Discord client
const client = new Discord.Client();
// Load config file
const config = require('./config.json');
client.config = config;
// Database config
const connection = mysql.createConnection({
  host: config.mysqlHost,
  user: config.mysqlUser,
  password: config.mysqlPassword,
  database: config.mysqlDatabase
});

// Check if ownerId is already in database
function checkOwnerId(authorId) {
  var query = connection.query(
    'SELECT * FROM guilds WHERE ownerId = ?', 
    authorId, 
    function (error, results, fields) {
      // Handle error after the release.
      if (error) throw error;
      // Debug
      console.log(query.sql);
      // If match
      if (results.length > 0) return "verified";
      else return "not_verified";
  });
}

/*
 * Event will run on every single message received, from any channel or DM.
 */
client.on('message', async msg => {
  // Ignore any message that does not start with prefix and ignore itself
  if (!msg.content.startsWith(config.prefix) || msg.author.bot) return;
  // Verify in database if the author.id is already saved
  if (checkOwnerId(msg.author.id) === "not_verified") {
    // Delete the command line
    msg.delete();
    // Send pm to author with error
    msg.author.send( 
      {embed: {
        color: 15934014,
        description: 'No permission to use the bot'
      }
    });
    console.log("NOT VERIFIED");
    return;
  }
  else {
    // Continue
  }

});

// Discord bot token
client.login(config.token);

如何在数据库中验证作者 id 是否已保存并让他使用一些命令?预先感谢您的帮助!

您可以这样做,这样您还可以进行进一步的 SQL 查询并处理结果:

const Discord = require('discord.js');
var mysql = require('mysql');
// Discord client
const client = new Discord.Client();
// Load config file
const config = require('./config.json');
client.config = config;
// Database config
const connection = mysql.createConnection({
    host: config.mysqlHost,
    user: config.mysqlUser,
    password: config.mysqlPassword,
    database: config.mysqlDatabase
});

// Check if ownerId is already in database
function sqlQuery(query, params) {
    return new Promise((resolve, reject) => {
        connection.query(
            query, params,
            (error, results) => {
                if (error) return reject(error);
                return resolve(results);
            });
    });
}

/*
 * Event will run on every single message received, from any channel or DM.
 */
client.on('message', msg => {
    // Ignore any message that does not start with prefix and ignore itself
    if (!msg.content.startsWith(config.prefix) || msg.author.bot) return;
    // Verify in database if the author.id is already saved
    sqlQuery('SELECT * FROM guilds WHERE ownerId = ?', msg.author.id,)
        .then(results => {
            if (results.length > 0) {
                //do stuff with verified user
            } else {
                msg.delete();
                // Send pm to author with error
                msg.author.send(
                    {embed: {
                            color: 15934014,
                            description: 'No permission to use the bot'
                        }
                    });
            }
        })
        .catch(error => {
            //handle error
        });
});

// Discord bot token
client.login(config.token);