Node.js 套接字IO回调未注册
我有一些NodeJS代码,使用socket io(版本2.4.1)。当调用靠近代码底部的条件时,例如Node.js 套接字IO回调未注册,node.js,socket.io,Node.js,Socket.io,我有一些NodeJS代码,使用socket io(版本2.4.1)。当调用靠近代码底部的条件时,例如if(!data.channel)或else if(data.channel!==data.session)时,如果没有setTimeout包装回调,则不会执行回调。即使这样,它也是间歇性的 socket.on("channel", (data, callback) => { logger.info({ message: "channel",
if(!data.channel)
或else if(data.channel!==data.session)
时,如果没有setTimeout
包装回调,则不会执行回调。即使这样,它也是间歇性的
socket.on("channel", (data, callback) => {
logger.info({ message: "channel", data: data });
let message = "no such channel";
if (data.channel && data.channel === data.session) {
session = checkSessionGivenData(data.session, data);
updateSessionData(session, data)
.then(() => {
getAsync(data.channel)
.then((jsonStringData) => {
let jsonData = JSON.parse(jsonStringData);
if (!jsonData) {
message = "failure establishing channel";
callback(message);
} else if (callback) {
callback(data.channel);
}
}).catch((err) => {
logger.error("Error in getAsync: " + err);
callback(message);
});
})
.catch((err) => {
logger.error("Error in updateSessionData: " + err);
callback(message);
});
} else if (callback) {
if (!data.channel) {
message = "missing channel in data";
} else if (data.channel !== data.session) {
message = "cannot establish channel other than to self";
} else {
logger.warn({ message: message, data: data });
}
// TODO: Without the timeout, the callback is not registered, we do not know why
setTimeout(function(){
callback(message);
}, 0);
}
});
这可能是什么原因造成的?这是在我的单元测试中发生的,开玩笑地说。如果我将超时移到那里,它工作正常。。。所以“错误”是因为我测试它的方式。