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