O
O
Oleg2020-08-17 12:23:51
JavaScript
Oleg, 2020-08-17 12:23:51

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), см. скрин.


Damn how?
Wangyu may be the fact that the answer comes a little later than it is assigned to the variable. Or it's a nested function.
In all examples and manuals of the Internet, the entire description ends with the phrase .... "And then we work as with a regular array." And here's how to get the result of working with a "regular array" now?
5f3a4c31b9a63880369123.png

Thank you very much in advance!
ps Maybe something sensible tell me where to look (read, listen), so as not to run into similar problems in the future)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2020-08-17
@VDT2

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.

A
Alexander, 2020-08-17
@Alexandre888

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 question

Ask a Question

731 491 924 answers to any question