在我的聊天程序中,我試圖創建一個函數,檢查數據庫中是否存在對話。如果與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 });
});
你的例子中data.result的輸出是什麼? – Mokkun
data.result輸出爲false – JonasSH
您錯過了回調點。您不會在回調中等待*,而是在回調中執行後續代碼*。 – shmosel