所有!
使用Node / Express / Socket.IO,我想重构相同的回调。
我有:
io.sockets.on('connection', function(socket) {
socket.on('find all notes' , function() { noteProvider.findAllNotes(function(err, result) {
if(err) {
socket.emit('err', err);
} else {
socket.emit('result', result);
}
}) });
socket.on('find note by id', function(id) { noteProvider.findNoteById(id, function(err, result) {
if(err) {
socket.emit('err', err);
} else {
socket.emit('result', result);
}
}) });
}
但想要的是:
io.sockets.on('connection', function(socket) {
socket.on('find all notes' , function() { noteProvider.findAllNotes(callback) });
socket.on('find note by id', function(id) { noteProvider.findNoteById(id, callback) });
}
如何重构回调?这两个例子不起作用:
不起作用1:
var callback = function(err, result) {
if(err) {
socket.emit('err', err);
} else {
socket.emit('result', result);
}
}
不起作用2:
io.sockets.on('connection', function(socket) {
socket.on('find all notes' , function() { noteProvider.findAllNotes(callback(socket, err, result)) });
socket.on('find note by id', function(id) { noteProvider.findNoteById(id, callback(socket, err, result)) });
}
与
var callback = function(socket, err, result) {
if(err) {
socket.emit('err', err);
} else {
socket.emit('result', result);
}
}
如何保持代码干净?
弗罗德
答案 0 :(得分:0)
如果你声明“无效1”,它可以访问套接字变量,那么它应该可以工作。这可以这样做:
io.sockets.on('connection', function(socket) {
var callback = function(err, result) {
if(err) {
socket.emit('err', err);
} else {
socket.emit('result', result);
}
}
socket.on('find all notes' , function() { noteProvider.findAllNotes(callback) });
socket.on('find note by id', function(id) { noteProvider.findNoteById(id, callback) });
});
似乎你试图在“不工作2”中解决这个问题,如果你在回调函数中返回一个函数,这将有效:
var callback = function(socket) {
// Returning the callback which will be called when noteProvider is done.
// Since it's in the closure of this function it will have a reference to socket.
return function (err, result) {
if(err) {
socket.emit('err', err);
} else {
socket.emit('result', result);
}
}
}
io.sockets.on('connection', function(socket) {
socket.on('find all notes' , function() { noteProvider.findAllNotes(callback(socket)) });
socket.on('find note by id', function(id) { noteProvider.findNoteById(id, callback(socket)) });
}