1

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

1 Answers1

0

In the function instead of console log you can put: return results.lengtg;

If that's what you wanted to do

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 10 '22 at 01:28