maxichrome
maxichrome

Reputation: 69

Wait for MySQL query in async function?

I'm querying my database in an async function (via the mysql library), but I can't seem to get my function to properly wait for the query to finish before continuing.

Code:

async (eventName, eventArgs, app) => {

  ...

  prefix = "!";

  if(msg.channel.type !== "dm")
    database.query(`SELECT prefix FROM guilds WHERE \`id\`=${msg.guild.id}`, (err, res) => {
      if(err)
        return console.error("db", `${err.message}`);

      if(res.length > 0)
        if(res[0].prefix)
          prefix = res[0].prefix;

      console.log(`from within callback ${prefix}`);
      console.log(`returned from query ${res[0].prefix}`);
    });

  console.log(`prefix in standard flow ${prefix}`);

  ...

}

The console outputs the following:

prefix in standard flow !
from within callback -
returned from query -

All 3 should output -, but outside the query callback it is !. It appears to be that my async function isn't waiting for the query callback function to finish before continuing, not a scope issue.

I've also tried awaiting the database.query function, but to no avail.

Upvotes: 3

Views: 3936

Answers (1)

PeterMader
PeterMader

Reputation: 7285

Using async/await:

async (eventName, eventArgs, app) => {
  let prefix = '!';
  const query = new Promise((resolve, reject) => {
    database.query(`SELECT prefix FROM guilds WHERE \`id\`=${msg.guild.id}`, (err, res) => {
      if(err)
        return reject("db", `${err.message}`);

      if(res.length > 0 && res[0].prefix)
          prefix = res[0].prefix;

      console.log(`from within promise ${prefix}`);
      console.log(`returned from query ${res[0].prefix}`);
      resolve();
    });
  });

  await query;
  console.log(`prefix in standard flow ${prefix}`);
}

Upvotes: 2

Related Questions