Answer the question
In order to leave comments, you need to log in
How to correctly get values from a nested function when working with mysql2?
Apparently, under the three hundredth line of the code, I became completely stupid ... I'm ashamed to ask, but I don't see a way out. I have read and studied everything I can think of. The "stone flower" does not come out...
var temp; // Объявил глобальную переменную
function getOnline(){ //функция возврата int значения из базы данных.
const sql = `SELECT * FROM Online`;
connection.query(sql, function(err, results) {
if(err) console.log(err);
for(let i=0; i < results.length; i++){ // Перебираем полученный массив и забираем значение.
temp=results[i].online; // Получаем корректный результат
}
});
}
console.log(temp); // 'undefined' не используемая переменная (как выдает IDE), см. скрин.
Answer the question
In order to leave comments, you need to log in
You need to "work like with a regular array" inside the callback - asynchronous code cannot be made synchronous. There are promises and async / await, but they do not fundamentally change the essence.
you need to read about variable scopes .
the temp variable you declared is undefined for console.log(temp) because its value is changed inside the function and is only available there.
if you want to output the modified temp, you must do so within a function:
var temp;
function getOnline(){
const sql = `SELECT * FROM Online`;
connection.query(sql, function(err, results) {
if(err) console.log(err);
for(let i=0; i < results.length; i++){
temp=results[i].online;
}
console.log(temp) // здесь temp = results[i].online
})
}
console.log(temp) // undefined, здесь temp не равняется ничему
getOnline();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question