Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Await result in js file with sqlite3

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use Promise constructor (mdn).

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading