我正在使用node mirc从mysql中检索数据
然后我希望使用以下代码将数据转换为数组:
function getQuestion (arr{
var obj = {};
connection.connect();
connection.query("SELECT * FROM quiz", function (err, rows, fields) {
if (err) throw err;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
obj = {"id":row.id, "question":row.question, "answers":row.answers.split(", ")};
f100.push(obj);
};
});
connection.end();
}
f100 = [];
getQuestion();
console.log(f100);
但是,它只打印[]
答案 0 :(得分:1)
connection.query
是异步的,因此我建议在f100
回调中安排connection.query
。如果您希望在完成填充后对f100
执行某些操作,则需要将其从连接查询回调中传递到另一个函数中。例如:
connection.query("SELECT * FROM quiz", function (err, rows, fields) {
if (err) throw err;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
obj = {"id":row.id, "question":row.question, "answers":row.answers.split(", ")};
f100.push(obj);
};
console.log(f100); // should console out correctly here
handleArray(f100); // passes in f100 to a new function
});
答案 1 :(得分:1)
由于.query()'s
异步行为,它需要一些时间来执行,但您在调用该函数后立即执行日志。您需要使用.query()
函数的回调来记录日志。
function getQuestion (arr{
var obj = {};
connection.connect();
connection.query("SELECT * FROM quiz", function (err, rows, fields) {
if (err) throw err;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
obj = {"id":row.id, "question":row.question, "answers":row.answers.split(", ")};
f100.push(obj);
};
// do log here
console.log(f100);
});
connection.end();
}
f100 = [];
getQuestion();