1

I have this code, which prints the correct result. I only want "example@gmail.com" in a variable:

[ RowDataPacket { CORREO: 'example@gmail.com' } ]
conexion.query("SELECT CORREO FROM ALUMNOS WHERE NOMBRE='RUBEN'", function (error, results, fields) {
    if (error) {
        throw error;
    }else{
        console.log(results)
    }
})

But when I want to save it in a variable, it gives me an error or undefined:

async function obtainEmail() {
    let result = await conexion.query("SELECT CORREO FROM ALUMNOS WHERE NOMBRE='RUBEN'", function (error, results, fields) {
        if (error) {
            throw error;
        }else{
            return results;
        }
    })
}

obtainEmail().then(data => console.log(data));

Result:

undefined

I have also tested:

let test = await obtainEmail();
console.log(test);

Result:

SyntaxError: await is only valid in async functions and the top level bodies of modules

Trying to save the query result ("example@gmail.com") in a variable

ruben2k1
  • 11
  • 2
  • Does this answer your question? [node.js async/await using with MySQL](https://stackoverflow.com/questions/44004418/node-js-async-await-using-with-mysql) – Jeremy Harris Dec 07 '22 at 17:13

1 Answers1

0

If you wrap your query function into a Promise, you will be able to use async / await.

const results = await new Promise((resolve, reject) => {
  conexion.query("SELECT CORREO FROM ALUMNOS WHERE NOMBRE='RUBEN'", function (error, results, fields) {
      if (error) {
        return reject(error);
      }
      resolve(results)
  })
})

In order to get rid of await is only valid in async functions error the function where this is being called has to have an async e.g.

(async () => {
  const results = await new Promise((resolve, reject) => {
    conexion.query(
      "SELECT CORREO FROM ALUMNOS WHERE NOMBRE='RUBEN'",
      function (error, results, fields) {
        if (error) {
          return reject(error);
        }
        resolve(results);
      }
    );
  });
})();
Max Blank
  • 46
  • 2
  • 4
  • I already have it, but with the code you gave me it keeps giving error: await is only valid in async functions – ruben2k1 Dec 07 '22 at 17:17
  • the function where you call `const results = await` has to have an `async` – Max Blank Dec 07 '22 at 17:23
  • @ruben2k1 just updated the code snippet above – Max Blank Dec 07 '22 at 17:26
  • I have it: async function obtenerEmail() { try { let result = await conexion.query("SELECT CORREO FROM ALUMNOS WHERE NOMBRE='RUBEN'", function (error, results, fields) { if (error) { throw error; }else{ return results; } }) } catch (error) { return error; } } obtenerEmail().then(data => console.log(data)); – ruben2k1 Dec 07 '22 at 17:29