在socket.io函數中,我在數據庫中創建新用戶並返回插入的id。但是我的函數在數據庫回調完成之前返回。所以,我得到了插入標識回客戶端:socket.io函數在回調完成前返回 - Node.js
io.on('connection',function (socket) {
socket.on('newUser',function (user) {
io.emit('newUser',createChatRoom(con,user.email,user.phone));
});
});
我創建用戶功能:
var createChatRoom = function (con, email, phone) {
con.query("SELECT * FROM USER WHERE `email`='" + email + "'", function (error, result) {
if (error) throw error;
if (result.length == 0) {
var chatToken = require('crypto').createHash('md5').update(email).digest("hex");
con.query("INSERT INTO user(email,chat_token,phone) VALUES('" + email + "','" + chatToken + "','" + phone + "')", function (error1, result1) {
return result1.insertId;
});
} else {
return "Old User";
}
});
};
提供回調createChatRoom funtion,以及從查詢的結果調用它。 – Edgar