1

Could someone explain me why I can't pass the rows Object to the clubs variable?

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'test'
});
var competition_feed = 'England';
var season_id = 2014;
var clubs = {};

connection.connect();

connection.query('SELECT * FROM clubs WHERE competition_feed=\''+competition_feed+'\' AND season_id='+season_id+';', function(err, rows, fields) {
    if (err) throw err;
    clubs = rows;
});

console.log(clubs);

connection.end();

It seems I'm missing something about variables and scope. Please help :)

2 Answers 2

1

You can, the reason this doesn't work is because

connection.query(.....)

Is asynchronous. So clubs isn't set to rows until later in the event loop. Much after you are trying to use it. One way to achieve the behavior you want is as follows:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'test'
});
var competition_feed = 'England';
var season_id = 2014;
var clubs = {};

connection.connect();

connection.query('SELECT * FROM clubs WHERE competition_feed=\''+competition_feed+'\' AND season_id='+season_id+';', function(err, rows, fields) {
    if (err) throw err;
    clubs = rows;
    logClubs();
});

function logClubs() {
    console.log(clubs);
}


connection.end();
Sign up to request clarification or add additional context in comments.

1 Comment

Thought it had something to do with 'asynchronousity' (if that's a word) but couldn't figure out how to exactly achieve this behaviour. Thanks :)
1

clubs = rows is executed asynchronously. If you put a console.log right before clubs = rows, you will see it actually executes afterwards despite coming first in the code.

2 Comments

Beat you to it by 21 seconds :)
Congrats! :( for me though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.