将对象分配给node.js中的变量

时间:2013-06-27 16:06:55

标签: node.js

有人可以解释一下为什么我无法将行Object传递给club变量吗?

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

我似乎对某些变量和范围缺失了一些东西。请帮助:)

2 个答案:

答案 0 :(得分:1)

你可以,这不起作用的原因是因为

connection.query(.....)

是异步的。因此,在事件循环的后期,俱乐部不会设置为行。在您尝试使用它之后很久。实现所需行为的一种方法如下:

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

答案 1 :(得分:1)

clubs = rows以异步方式执行。如果你在console.log之前放置一个clubs = rows,你会发现它实际上是在事后执行的,尽管它在代码中排在第一位。