我无法将以下代码块重构为单独的函数。
BootstrapMethods:
0: #40 invokestatic java/lang/invoke/LambdaMetafactory.metafactory:(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;
Method arguments:
#41 ()V
#42 invokestatic L.lambda$main$0:()V
#41 ()V
我尝试重构上面的代码如下。
#41 = MethodType #18 // ()V
#42 = MethodHandle #6:#59 // invokestatic L.lambda$main$0:()V
#43 = NameAndType #57:#60 // run:()Ljava/lang/Runnable;
#44 = Utf8 here
#45 = NameAndType #54:#61 // println:(Ljava/lang/String;)V
#46 = Utf8 L
#47 = Utf8 java/lang/Object
#48 = Utf8 java/lang/System
#49 = Utf8 out
#50 = Utf8 Ljava/io/PrintStream;
#51 = Utf8 getClass
#52 = Utf8 ()Ljava/lang/Class;
#53 = Utf8 java/io/PrintStream
#54 = Utf8 println
#55 = Utf8 (Ljava/lang/Object;)V
#56 = Utf8 java/lang/Runnable
#57 = Utf8 run
由于未定义套接字,我收到运行时错误。
如何在'doLogin'函数中引用'socket'?
我也尝试了以下方法,但无法使其正常工作。
socketHandler = (io) => {
io.on('connection', (socket) => {
socket.on('doLogin', data => {
userService.getUserByName(data.uname)
.then((doc) =>{
if(doc && doc.pwd===data.pwd){
socket.emit('onLogin', {status:'SUCCESS'});
}
}, (error) => {
socket.emit('onLogin', {status:'Error in the application'});
});
});
});
}
app.configure(socketio(socketHandler));
还尝试如下
doLogin = data => {
userService.getUserByName(data.uname)
.then((doc) =>{
if(doc && doc.pwd===data.pwd){
socket.emit('onLogin', {status:'SUCCESS'});
}
}, (error) => {
socket.emit('onLogin', {status:'Error in the application'});
});
}
socketHandler = (io) => {
io.on('connection', (socket) => {
socket.on('doLogin', doLogin);
});
}
app.configure(socketio(socketHandler));
需要一些帮助来解决这个问题。
感谢。
答案 0 :(得分:2)
在您分解函数后,您丢失了对socket
对象的引用。你可以尝试在SocketHandler
socket.on('doLogin', (data) => doLogin(data, socket));
并将doLogin
重新定义为
doLogin = (data, socket) => {
答案 1 :(得分:0)
doLogin.bind(socket)
是箭头功能,则 doLogin
无法工作,因为箭头功能无法绑定。相反,它应该是一个常规功能:
function doLogin(data) {
const socket = this;
...
}
...
socket.on('doLogin', doLogin.bind(socket));