Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

450
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda