我需要在另一个函数内部对mysql进行sql查询,并在主函数返回值后收到查询结果
connectionPool.getConnection(function (err, connection) {
connection.query("SELECT * FROM `sys_menu_top` WHERE `Type` = 'top' AND Active = 1 ORDER BY `Order`", function (err, rows, fields) {
if (rows) {
async.each(rows, function (row, callback) {
row.children = [];
connectionPool.getConnection(function (err, connection, sql) {
connection.query("SELECT * FROM `sys_menu_top` WHERE Parent = " + row.ID, function (err, children, fields) {
// console.log(children);
if (!err && children.length > 0) {
children.forEach(function (child) {
row.children.push(child);
});
row.children.push(children);
}
else {
console.log(err);
}
});
});
callback();
}, function (err) {
if (err)
console.error('error looping array\n\n');
});
process.nextTick(function () {
cb(null, rows);
});
}
});
});
我的代码返回没有子节点的行但是我可以在函数返回第一个查询结果后在控制台中接收子节点。我需要将每行的子项放入此行,然后返回结果。
答案 0 :(得分:0)
我知道它有不同的方法,但值得尝试以下内容:
async.waterfall([
function (callback) {
var q = "SELECT * FROM Rows";
executeQuery(q, function(err, rows, fields) {
if (err) { callback(err); return; };
if (rows) {
callback(null, rows);
return;
}
});
},
function (rows, callback) {
console.log(rows);
for (k in rows) {
if (rows[k].Parent != null) {
child = rows[k].id;
parent = rows[k].Parent;
for (j in rows) {
if (rows[j].id == parent) {
if (!rows[j].Children) rows[j].Children = [];
rows[j].Children.push(child);
}
}
}
}
callback(null, rows);
}
],
function (err, rows) {
console.log(rows);
});
我的测试表得到的是:
[ { id: 1, Parent: null },
{ id: 2, Parent: 1 },
{ id: 3, Parent: 1 } ]
[ { id: 1, Parent: null, Children: [ 2, 3 ] },
{ id: 2, Parent: 1 },
{ id: 3, Parent: 1 } ]