batomaeus batomaeus - 1 month ago 6
Javascript Question

node.js refactoring: How to pass object-pointer (here: a socket)?

Goal



Avoiding "callback hell" in node.js.

Problem



The socket-object is not available anymore after refactoring.
How can it be passed to the function?

Before refactoring



server.js



var ActiveSession = require('./session-model');

// ...

socket.on("c2s_logout", function (message) {
ActiveSession.remove({ sessionid: message.sessionid } , function(err, activeSession) {
socket.emit("s2c_logout_success");
});
});


After refactoring



auth.js



var ActiveSession = require('./session-model');
function logout(message) {
ActiveSession.remove({ sessionid: message.sessionid } , function(err, activeSession) {
//socket.emit("s2c_logout_success"); // THE PROBLEM
// THIS IS NOT POSSIBLE ANYMORE AFTER REFACTORING
// SOCKET IS NOT AVAILABLE
});
}
module.exports.logout = logout;


server.js



var Auth = require('./auth.js');

// ...

socket.on("c2s_logout", Auth.logout );

Answer

Taken the answer from Alnitak, but corrected syntactically. Version is tested successfully.

server.js

socket.on('c2s_logout',(message)=>{
    Auth.logout(message,(err)=>{
        if (err) {
            // logout failed
        } else {
            socket.emit('s2c_logout_success');
        }
    })
});

auth.js

function logout(message, callback) {
    ActiveSession.remove({sessionid: message.sessionid}, (err, activeSession) => 
        callback(err)
    )
}
Comments