Home > Net >  SQL output undefined when using it outside the function
SQL output undefined when using it outside the function

Time:06-10

I am trying to execute SQL results outside it's function. This is my code:

var rows;
var fields;

const connection = await mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'root'
});

connection.connect(
    (err) => {
        if(err) {
            console.log(err);
            process.exit(0);
        }
        
        console.log('logged in!');        
    }
);

async function query() {
    [rows, fields] = await connection.execute("SELECT plan FROM users WHERE username = 'onyx'");
    console.log(rows);
}

console.log(rows);
query();

First console.log(rows); gives correct output but once I put it outside the function, I get error undefined.

I know there are questions about this but I need better understanding and explanation about this...

I am using sync now as told but still same problem.

CodePudding user response:

You have an async function query() and you are trying to log 'rows' inside and outside the function, according to your code, you have

console.log(rows);
query();

this way, the log inside the function will surely return an output because it is being filled by the query above it, but if u try to log outside, it will not and that's because u didn't await qeury() to finish.

to get it working:

await query();
console.log(rows)

this way, rows will be filled before logging because you are filling rows with an async function which has to be awaited

  • Related