简体   繁体   中英

How can I save the query result in a variable using the mysql library in NodeJS?

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

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 eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM