I rewrite my code from Python to Node.js I need to get some data from SQL and then use it in the code after. So it is easy with python, you just get it, return and you can use it.
The code in Python
def sql_get_new_id(connection):
with connection.cursor() as cursor:
sql = "SELECT * FROM `item` WHERE 1"
cursor.execute(sql)
result = cursor.fetchall()
return len(result) # <==== So you just can get this data and use it out of the loop
print(sql_get_new_id()) # <==== Right here it works perfectly
But in JS as i see i cant just get it with return at the end of the function. You can only see it at the console. So how do i get it now?
const mysql = require("mysql2");
const sql = `SELECT * FROM item WHERE 1`;
connection.query(sql, function(err, results) {
if(err) console.log(err);
console.log(results.length); // <===== I can do a console log
return results.length; // <====== But returning doesn't let me use it out of the loop
});
connection.end();
}
console.log(sqlGetNewId()) // <==== There is no data i need