我正在使用mysql数据库在节点js中开发一个项目。我想在index.j文件中执行查询。代码适用于两个连接但是当我添加第三个查询时,我不知道在结果[] []中使用什么数字。你能帮忙吗?谢谢。
这是index.js文件中的代码
router.get('/StudentPage', function (req, res, next) {
if (req.session && req.session.user) {
pool.getConnection(function (err, connection) {
async.parallel([
function (callback) { connection.query('select * from students where Email = ' + connection.escape(req.session.user.Email), callback) },
function (callback) { connection.query('select * from reservations where student_email = ' + connection.escape(req.session.user.Email), callback) },
function (callback) { connection.query('select * from complaint where student_email = ' + connection.escape(req.session.user.Email), callback)}
], function (err, results) {
if (!results[0][0]) {
req.session.reset();
res.redirect('/');
} else {
res.render('student', { title: 'Student Page', userinfo: results[0][0], reservations: results[1][0], complaints: results[2][0]});
}
connection.release();
});
});
} else {
res.redirect('/');
}
});
答案 0 :(得分:1)
尝试使用键值对象而不是async.parallel
// an example using an object instead of an array
async.parallel({
one: function(callback){
setTimeout(function(){
callback(null, 1);
}, 200);
},
two: function(callback){
setTimeout(function(){
callback(null, 2);
}, 100);
}
},
function(err, results) {
// results is now equals to: {one: 1, two: 2}
});
例如:
router.get('/StudentPage', function (req, res, next) {
if (req.session && req.session.user) {
pool.getConnection(function (err, connection) {
async.parallel({
students: function (callback) {
connection.query('select * from students where Email = ' + connection.escape(req.session.user.Email), callback)
},
reservations: function (callback) {
connection.query('select * from reservations where student_email = ' + connection.escape(req.session.user.Email), callback)
},
complaints: function (callback) {
connection.query('select * from complaint where student_email = ' + connection.escape(req.session.user.Email), callback)
}
}, function (err, results) {
if (!results.students || !results.students[0]) {
req.session.reset();
res.redirect('/');
} else {
res.render('student', {
title: 'Student Page',
userinfo: results.students[0],
reservations: results.reservations[0],
complaints: results.complaints[0]
});
}
connection.release();
});
});
} else {
res.redirect('/');
}
});