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.