jenoh
jenoh

Reputation: 179

How to make an async function with mysql in node.js

I try to store the result of my mysql request into and async function (to make something after storing my result) but it's returning undefined.. I don't know why

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();

Upvotes: 0

Views: 62

Answers (1)

BENARD Patrick
BENARD Patrick

Reputation: 31005

You're not returning a promise... Try with this code, it could help...

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();

Upvotes: 1

Related Questions