'How do I get the information from the database before sending a message

I'm currently making a discord bot with discord.js v13. Right now I have a database where the guild.id and the standard prefix of a server are stored in. Now I want to rewrite a command which gets triggered by the prefix and the name of the command, like this '!somecommand'. Currently my prefix is defined in the file with a const variable, but I want the bot to check the database for the prefix the server has, and use this one instead. I'm checking the prefix in the database with this part of code:

pool.getConnection(function(err, connection) {
  if (err) throw err;
  let sql = `SELECT * FROM custom_prefix WHERE guild_id = '${message.guild.id}'`;
  connection.query(sql, async function (err, result) {
      if (err) throw err;
      console.log(result[0].prefix)
      connection.release();
  });
});

The output is the current prefix of the server where the command was triggered, so far everything works fine. But as I said I want the output of the code above to be the prefix with which the bot gets triggered.

I already tried to do it, but I'm always making a mistake. Most of the time the bot is checking the database too slow and the result will be 'undefined'. I dont know how I make the bot to wait for the result from the database, check if this result is really the prefix and then execute the command.

I am happy about any answer :-) If you need any more information please let me know.



Solution 1:[1]

I'm guessing you did put the code that uses the result outside of the callback.

pool.getConnection(function(err, connection) {
  if (err) throw err;
  let sql = `SELECT * FROM custom_prefix WHERE guild_id = '${message.guild.id}'`;
  connection.query(sql, async function (err, result) {
      if (err) throw err;
      console.log(result[0].prefix)
      connection.release();
      //
      // Put your code that uses result[0].prefix here
      //

  });
});

//
// Do not put your code that uses result[0].prefix here
//

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Simon Groenewolt