简体   繁体   English

使用箭头函数重构嵌套函数

[英]Refactoring nested functions with arrow functions

I have trouble in refactoring the following code block into separate functions. 我在将以下代码块重构为单独的函数时遇到麻烦。

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));

I tried refactoring the above code as follows. 我尝试如下重构上述代码。

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));

I am getting a run-time error as socket is not defined. 由于未定义套接字,因此出现运行时错误。

How to get reference to 'socket' in the function 'doLogin'? 如何在函数“ doLogin”中引用“ socket”?

I also tried the following way and could not make it work. 我也尝试了以下方法,但无法使其正常工作。

doLogin = socket => data => {

Also tried as follows 也尝试如下

socket.on('doLogin', doLogin.bind(socket));

Need some help in fixing this. 需要一些帮助解决此问题。

Thanks. 谢谢。

After you broke up the functions you lost reference to socket object. 分拆功能后,您将失去对socket对象的引用。 You could try, in SocketHandler 您可以在SocketHandler中尝试

socket.on('doLogin', (data) => doLogin(data, socket));

and redefine doLogin as 并将doLogin重新定义为

doLogin = (data, socket) => {

doLogin.bind(socket) won't work if doLogin is arrow function, because arrow functions cannot be bound. 如果doLogin是箭头功能,则doLogin.bind(socket)将不起作用,因为箭头功能无法绑定。 Instead, it should be a regular function: 相反,它应该是一个常规函数:

function doLogin(data) {
  const socket = this;
  ...
}
...
socket.on('doLogin', doLogin.bind(socket));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM