gpt4 book ai didi

javascript - 如何让一个函数在继续之前等待回调

转载 作者:太空宇宙 更新时间:2023-11-03 11:38:16 25 4
gpt4 key购买 nike

在我的聊天程序中,我试图创建一个函数来检查数据库中是否存在对话。如果存在与 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 });
});

最佳答案

这看起来像 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 注入(inject)攻击。请了解参数化查询在您使用的 SQL 库中的工作原理,并使用它们而不是构建 SQL 查询用 +!

关于javascript - 如何让一个函数在继续之前等待回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43886001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com