1

全部!

使用 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);
    }
}

我怎样才能保持我的代码干燥?

弗罗德

4

1 回答 1

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)) });
}
于 2013-03-18T14:44:16.527 回答