I’ve been trying to solve this problem for 2 days and have basically gone through everything I could find here on stackoverflow, maybe I’m missing something since I’ve been staring at it for so long.
I have a nodejs file which loads user data via sql and sends the result to the main file (server).
I call this function again with an async function to get the value of the row.
var sql = require('./db');
let h = /^[a-zA-Z-_.d ]{2,180}$/;
async function getdata(hash){
if (!hash || !hash.match(h)) {
return {type: "error", msg:"Verarbeitungsfehler, bitte laden Sie die Seite neu.", admin: false}
}else{
const response = await sql.query('SELECT * FROM bnutzer WHERE hash = ?',[hash], async function(err, result, fields){
//console.log(result)
return await result
})
}
}
module.exports = { getdata };
async function getvalue(h){
try{
var result = await admin.getdata(h);
console.log('1'+result);
if(result{
console.log('2'+result)
}
}catch(err){
console.log(err);
console.log('Could not process request due to an error');
return;
}
}
getvalue(user.ident)
The data from the sql query are correct and they also return the correct result when I output them in the console, however they are not passed with return to the function with which I call the code, it comes only undefined, I have the feeling that await here somehow does not wait for the result, what am I missing here? I have already tried it with several constellations that I could find on the internet, unfortunately I have not yet come to the goal.
I already tried not writing the sql query with async/await and only writing the calling function with async/await, no result. I have tried various sql query with and without sql callback. I hope someone can point me to what I am twisting or missing here.
2
Answers
the method in which you are executing query is incorrect you should do something like this
try this you cant mix callback and await like the way you’re doing just await for the result and in case of error it’ll handled by catch block in this case
Your async callback function will just return it in
response
variable in a good case. But anyway , use return await in nested async function is not a best way. So , yourresult
will become aresponse
variable , you’re not doing anything with it and it just will stay as it is , without return value. So , then you’ll have a plain function andundefined
as a result of it’s execution. Since you’re not returning anything from there.I suggest to :
And then :