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.
awaita promise.database.queryfunction, then resolve the promise once the value ofprefixhas been set?mysql2, which has built-in promise support.