gpt4 book ai didi

javascript - Node.js 重构 : How to pass object-pointer (here: a socket)?

转载 作者:行者123 更新时间:2023-12-02 14:10:37 24 4
gpt4 key购买 nike

目标

避免 Node.js 中的“回调 hell ”。

问题

重构后套接字对象不再可用。如何将其传递给函数?

重构前

服务器.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");
});
});

重构后

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;

服务器.js

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

// ...

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

最佳答案

您可以将套接字传递给注销函数。

auth.js

var  ActiveSession = require('./session-model');
function logout(message, socket) {
ActiveSession.remove({ sessionid: message.sessionid } , function(err, activeSession) {
socket.emit("s2c_logout_success"); // NO PROBLEM

});
}
module.exports.logout = logout;

服务器.js

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

// ...

socket.on("c2s_logout", function(message){ Auth.logout(message, socket); });

关于javascript - Node.js 重构 : How to pass object-pointer (here: a socket)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39634830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com