why I cannot get results?
var sql_data = connection.query(sql, function(error, results, fields) {
if(error) {
console.log(error);
return;
}
var rows = JSON.parse(JSON.stringify(results[0]));
console.log(rows);
});
console.log(rows);
fiirst console.log is ok, display object, but second says:
ReferenceError: rows is not defined
what is wrong?..
You shouldn't assign asynchronous function to a variable just like you do in first line of your code. You just call it and perform operations on the result with use of callback
methods (which in this case is function(error, results, fields)
. Your code should look like below
connection.query(sql, function(error, results, fields) {
if(error) {
console.log(error);
return;
}
var rows = JSON.parse(JSON.stringify(results[0]));
// here you can access rows
console.log(rows);
});
// here it will be undefined
console.log(rows);
The rows
variable in second console.log
will be undefined because it was defined in different scope. Even if you would do var rows
above the connection.query
, it would still be undefined, because you assign it's value inside asynchronous function's callback. You need to read more about this kind of operations.
You should use then Promise if you want to get the query result. I prefere it to be onest. The Promise runs the command async.
function getDomain() {
return result = await dbQuery('SELECT name FROM virtual_domains ORDER BY id;');
}
// * Important promise function
function dbQuery(databaseQuery) {
return new Promise(data => {
db.query(databaseQuery, function (error, result) { // change db->connection for your code
if (error) {
console.log(error);
throw error;
}
try {
console.log(result);
data(result);
} catch (error) {
data({});
throw error;
}
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With