在我的聊天程序中,我正在尝试创建一个函数,用于检查数据库中是否存在对话。如果与peopleName
存在对话,则应在客户端上检索该对话。如果不存在具有该名称的会话,则应创建新会话。
似乎' checkConversation'函数不等待结果,因为它每次都在创建一个新的对话,即使对话存在。
客户端:
//Starting conversation
$("#people").on("click", ".list-group-item", function() {
var peopleName = $(this).children("span").text();
var peopleID = $(this).children("span").attr("class");
var conversationExists = false;
socket.emit("checkConversation", peopleName, function(data) {
conversationExists = data.result;
if (conversationExists) {
console.log("Retrieved existing conversation with ", peopleName);
return;
// Check if there is a conversation in the Database where this name is conversationReceiver. ------------------------------------
// if there is: retrieve conversation/messages
// else: create conversation.
} else {
console.log("NEW conversation with ", peopleName);
socket.emit("serverCreateConversation", peopleName, peopleID);
$("#msg").prop("readonly", false);
$("#msg").attr("placeholder", "Your message");
$("#send").attr("disabled", false);
$("#chat").empty();
}
});
});

服务器端:
client.on("checkConversation", function(peopleName, fn) {
var match = false;
connection.query("SELECT * FROM `conversations` WHERE `conversation_receiver` = '" + peopleName + "'", function(error, results, fields) {
if (error) {
console.log(error);
} else if (results) {
console.log("Conversation exists!", results);
match = true;
} else {
console.log(fields);
}
});
console.log("match: " + match);
fn({ result: match });
});

答案 0 :(得分:2)
这似乎是the usual asynchronous callback hurdle人在开始使用Node.js和其他Javascript异步时偶然发现的。
服务器端,当你从数据库中获得结果时,你需要只调用fn
,即在传递给connection.query
的回调中:
client.on("checkConversation", function(peopleName, fn) {
connection.query("SELECT * FROM `conversations` WHERE `conversation_receiver` = '" + peopleName + "'", function(error, results, fields) {
if (error) {
console.error(error);
fn({ result: false, error: true });
return;
}
var match = !!results; // (shorthand to turn a truthy value into true/false)
console.log("Conversation with " + peopleName + ": " + match);
fn({ result: match });
});
});
(我冒昧地简化了代码。)
但是,还有一个紧迫的问题:您的代码容易受到SQL注入攻击。请查看参数化查询如何在您正在使用的SQL库中工作,并使用它们而不是构建SQL查询与+
!
答案 1 :(得分:1)
你做错了,websocket不能像AJAX那样工作,你需要从你的后端发出结果,并在你的前端听它
您的服务器代码需要socket.emit
并且您需要在客户端代码上使用socket.on