Home > Net >  Await result in js file with sqlite3
Await result in js file with sqlite3

Time:06-24

I'm a discord bot developer and I use a database.db file as a database. I code in JS so i installed the sqlite3 module. My code for the 'messageCreate' event is right there:

module.exports = {
  name: "messageCreate",
  once: false,
  async execute(client, message) {
    let prefix;
    await client.db.get(
      `SELECT prefix FROM "Guilds" WHERE id = "${message.guild.id}"`,
      async (err, row) => {
        prefix = row.prefix;
      }
    );
    if (message.author.bot) return;
    if (!message.content.startsWith(prefix)) return;

    const args = message.content.slice(prefix.length).trim().split(/  /g);
    const cmdName = args.shift().toLowerCase();

    if (cmdName.length == 0) return;

    let cmd = client.commands.get(cmdName);
    if (cmd) {
      cmd.run(client, message, args);
    }
  },
};

I want to put the resut of the .get() function in the prefix variable, but when I try to run the code, it returns undefined, so I did a console.log() and saw that the code didn't await the result and continued to run. So the problem is that I don't know how to await the result of the .get() function. I tried to put an await, but i didn't do anything. Is there another way to wait the result and then create a variable with the result in it?

CodePudding user response:

Use Promise constructor (mdn).

const prefix = await new Promise((resolve, reject) =>
  client.db.get(SQL,
    (err, row) => err ? reject(err) : resolve(row.prefix)
  )
)

CodePudding user response:

Could you check if there's an error? I speculate that you have an error in your SQL syntax, since you are putting quotes around the table name here:

SELECT prefix FROM "Guilds" WHERE id = "${message.guild.id}"
                   ^^^^^^^^

Add this for troubleshooting purposes and let me know what it returns:

      async (err, row) => {
        if (err) throw err;
        prefix = row.prefix;
      }
  • Related