1

有人可以解释一下为什么我不能将 rows 对象传递给 clubs 变量吗?

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

看来我错过了一些关于变量和范围的东西。请帮忙 :)

4

2 回答 2

1

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

connection.query(.....)

是异步的。所以 clubs 直到事件循环的后期才设置为 rows。在您尝试使用它之后。实现您想要的行为的一种方法如下:

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();
于 2013-06-27T16:08:56.717 回答
1

clubs = rows是异步执行的。如果你console.log在前面加上一个 right clubs = rows,你会看到它实际上是在之后执行的,尽管它在代码中排在第一位。

于 2013-06-27T16:09:14.093 回答