我有这样的代码:
exports.get_menu = function(req, fn) {
var sql_query = "SELECT id,parent_id,nama,target,keterangan,urutan,status";sql_query +=" FROM tbl_menu WHERE parent_id=0 ORDER BY urutan ASC";
var query = koneksi.query(sql_query, function(err, rows) {
if (err) {
throw err;
console.log(err);
} else {
rows.forEach(function(d) {
var sql_query2 = "SELECT id,parent_id,nama,target,keterangan,urutan,status";sql_query2 +=" FROM tbl_menu WHERE parent_id = "+d.id+" ORDER BY urutan ASC";
var query2 = koneksi.query(sql_query2, function(err, rows2) {
if (err) {
return fn(false, err);
console.log(err);
} else {
return fn(true, rows2)
};
});
);
}
});
};
总是会导致错误。
答案 0 :(得分:1)
你在forEach循环中使用db query,每次调用fn函数都是错误的。要避免无法设置标头错误,请使用promise或async模块。
var async = require('async');
exports.get_menu = function(req, fn){
var sql_query = "SELECT id,parent_id,nama,target,keterangan,urutan,status";
sql_query +=" FROM tbl_menu WHERE parent_id=0 ORDER BY urutan ASC";
var query = koneksi.query(sql_query,function(err,rows){
if(err) {
console.log(err);
throw err;
} else {
var result = [];
async.each(rows, function(row, callback){
var sql_query2 = "SELECT id,parent_id,nama,target,keterangan,urutan,status";
sql_query2 +=" FROM tbl_menu WHERE parent_id = "+row.id+" ORDER BY urutan ASC";
var query2 = koneksi.query(sql_query2,function(err,rows2){
if(err) {
return callback(err);
}
else{
result.push(rows2);
return callback()
};
});
}, function(err){
if(err){
console.log(err);
return fn(false, err);
}
else{
return fn(true, result);
}
})
}
});
};