Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

454
Vistas
Node.js and SQL: How can I get the value outside of the for loop?

Using Node.js and a MySQL database I'm working on a small project.

I'm trying to loop through an array to get some values out of a MySQL database. I'm searching for the corresponding "medicine ID" to an "medicine name" that the user entered. My Code is working correctly and this is how it looks.

var medizinArray = [];

function appendArray(input) {
  medizinArray.push(input);
}

var sqlMedNameToId = "SELECT MedikamentId FROM Medikament WHERE Bezeichnung = ?"

for (var i=0;i<medicineMontag.length;i++){
  var montagsMedizin = medicineMontag[i];
  mySqlConnection.query(sqlMedNameToId, montagsMedizin, function(err, rows, fields){
    if(!err) {
      result = rows[0].MedikamentId;
      appendArray(result);
    } else {
      console.log(err);
      }
  })
}

console.log(medizinArray);

The code is working but I can't get the medizinArray out of the for loop. In my console I get an empty array. When I put the console.log(medizinArray) inside the for loop I get the array that I want.

I'm currently not familiar with Promises. I read about it and saw some other questions but I can't figure out how to implement Promises in my code.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

SQL operations are asynchronous, so to obtain the result outside of the callback you need to wrap them in a Promise and call the resolve() function when the operation is successful. Use any of the techniques below:

Async/await technique:

(async function(){
  let medizinArray = [];

function appendArray(input) {
  medizinArray.push(input);
}

let sqlMedNameToId = "SELECT MedikamentId FROM Medikament WHERE Bezeichnung = ?"
await new Promise(function(resolve, reject){
let e;
for (let i=0;i<medicineMontag.length;i++){
  let montagsMedizin = medicineMontag[i];
  mySqlConnection.query(sqlMedNameToId, montagsMedizin, function(err, rows, fields){
    if(e) return; 
    if(!err) {
      result = rows[0].MedikamentId;
      appendArray(result);
    } else {
      //console.log(err);
      e = true; 
      return reject(err);
      }
    if(i == medicineMontag.length-1) resolve(result);
  })
}
}
);

console.log(medizinArray);//now medizinArray shows up here
})().catch(function(err){console.log(err)});

Promise/then technique:

let medizinArray = [];

function appendArray(input) {
  medizinArray.push(input);
}

let sqlMedNameToId = "SELECT MedikamentId FROM Medikament WHERE Bezeichnung = ?"

new Promise(function(resolve, reject){
let e; 
for (let i=0;i<medicineMontag.length;i++){
  let  montagsMedizin = medicineMontag[i];
  mySqlConnection.query(sqlMedNameToId, montagsMedizin, function(err, rows, fields){
    if(e) return;
    if(!err) {
      result = rows[0].MedikamentId;
      appendArray(result);
    } else {
      console.log(err);
      e = true; 
      return reject(err); 
      }
    if(i == medicineMontag.length-1) resolve(result);
  })
}
}
).then(function(result){
console.log(medizinArray);//now medizinArray shows up here
}).catch(function(err){
  console.log(err);
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda