我是nodejs的新手。我正在使用nodeJs开发一个演示应用程序。运行多个查询时出现问题。我的代码如下:
exports.dashboard = function(req, res){
req.getConnection(function(err,connection){
var id = req.session.userId;
var queryData = "SELECT node_questions.question_name,node_questions.description FROM node_questions LEFT JOIN node_user ON node_questions.user_id=node_user.id";
var query = connection.query(queryData,'SELECT * FROM node_user Where id = ?',[id],function(err,rows)
{
console.log(rows);
res.render('dashboard',{page_title:"Dashboard",session:req.session.userId,email:req.session.email,data:rows});
});
});
};
数据库连接是:
app.use(
connection(mysql,{
host: 'localhost',
user: 'root',
password : 'password',
port : 3306, //port mysql
database:'nodeDemo',
multipleStatements:true
},'pool') //or single
);
答案 0 :(得分:1)
为什么不使用Promise?
let Promise = require('bluebird'),
begin = []
begin.push(promise1(a,b))
begin.push(promise2(c.d))
return Promise.all(begin)
.spread(function (resultFromQuery1, resultFromQuery2) {
// do something with the result here
})
答案 1 :(得分:1)
你把东西混在一起。例如,您对rows
的期望是什么?它应该是第一个还是第二个查询的结果集?处理这个的一个好方法是使用异步模块(确保首先通过你的package.json中的npm安装它。)
var async = require('async');
var mysql = require('mysql');
client = mysql.createConnection({
user: 'root',
password : 'password',
port : 3306, //port mysql
database:'nodeDemo',
multipleStatements:true
});
var id = req.session.userId;
async.parallel([
function(callback) {
var queryData = '' +
' SELECT node_questions.question_name,node_questions.description' +
' FROM node_questions' +
' LEFT JOIN node_user' +
' ON node_questions.user_id=node_user.id';
client.query(queryData, function (err, rows1) {
if (err) {
return callback(err);
}
return callback(null, rows1);
});
},
function(callback) {
client.query('SELECT * FROM node_user Where id = ?', id, function (err, rows2) {
if (err) {
return callback(err);
}
return callback(null, rows2);
});
}
], function(error, callbackResults) {
if (error) {
//handle error
console.log(error);
} else {
console.log(callbackResults[0]); // rows1
console.log(callbackResults[1]); // rows2
// use this data to send back to client etc.
}
});