Onyx
Onyx

Reputation: 15

SQL output undefined when using it outside the function

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.

Upvotes: 0

Views: 283

Answers (1)

Mohammed Faour
Mohammed Faour

Reputation: 948

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 query() 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

Upvotes: 1

Related Questions