在异步函数中等待MySQL查询?

时间:2017-08-04 17:46:57

标签: javascript mysql node.js asynchronous

我在异步函数中查询我的数据库(通过mysql库),但我似乎无法让我的函数在继续之前正确等待查询完成。< / p>

代码:

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}`);

  ...

}

控制台输出以下内容:

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

所有3都应输出-,但在查询回调之外,它是!。似乎我的异步函数不等待查询回调函数在继续之前完成,而不是范围问题。

我还试过await database.query函数,但无济于事。

1 个答案:

答案 0 :(得分:0)

使用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}`);
}