【发布时间】:2016-03-22 13:15:58
【问题描述】:
考虑到我的 server.js 看起来几乎像这样。只需将相关部分发送给您。我没有从查询中收到任何信息,我确实在数据库中有数据,并且“sendNotification”是由客户端中的 jQuery 函数触发的。一切正常,因为 var notis = [];返回一个空值,并显示为响应。我知道我必须调试 SQL,这就是我要做的,但无论如何我想确定其他事情。所以我的问题是:
1) 考虑到这种异步行为,node.js 的语法是否正确? (我还是不明白)
2) 查询总是应该在“io.sockets.on('connection')”部分内?
connection = mysql.createConnection({
host: 'localhost',
user: '',
password: "",
database: 'table' //put your database name
}),
...
connection.connect(function(err) {
// connected! (unless `err` is set)
console.log(err);
});
…
var sqlquery = function(uID,vs){
var notis = [];
connection.query("SELECT * FROM notification WHERE kid = ? AND v = ? ORDER BY id DESC",[uID,vs])
.on("result", function (data){
return notis.push(data);
});
};
io.sockets.on('connection', function(socket) {
...
socket.on("sendNotification", function(data) {
var roomBName = data.room_name.replace("room-",""),
found = [];
var roomSelected = _.find(rooms, function (room) { return room.id == roomBName });
for (var person in people) {
for (var i = 0, numAttending = roomSelected.peopleAttending.length; i < numAttending; i++) {
if (people[person].name == roomSelected.peopleAttending[i]) {
found.push(person);
}
}
}
for (var i = 0, numFound = found.length; i < numFound; i++) {
**result = sqlquery(9,2);**
io.to(found[i]).emit('notification', result);
};
});
【问题讨论】: