如何在node.js中使用mysql制作异步功能

时间:2019-12-20 14:09:08

标签: mysql node.js asynchronous async-await

我尝试将mysql请求的结果存储到and异步函数中(在存储结果后做一些事情),但返回的是未定义的。。我不知道为什么

function hh () {
  connection.query('SELECT * FROM `rounds` ', function (error, results, fields) {
    if (error) throw error;
    // console.log(results)
    return results
  });
}

async function run() {
  connection.connect();
  let deter = await hh();
  console.log(deter)
  connection.end();
}

run();

1 个答案:

答案 0 :(得分:1)

您没有兑现承诺...尝试使用此代码,可能会有所帮助...

function hh () {
  return new Promise((resolve, reject) => {
      connection.query('SELECT * FROM `rounds` ', function (error, results, fields)   {
          if (error) return reject(error);
          // console.log(results)
          resolve(results)
      });
  });
}

async function run() {
  connection.connect();
  let deter = await hh();
  console.log(deter)
  connection.end();
}

run();