Passing socket as a Socket.io Param?

Broadly, I have the following workflow:

  1. User asks for an article with a certain title
  2. Client side, Socket.io emits an event and passes the title as data
  3. Server side, node fires an http request to an API and gathers relevant information about that article
  4. When finished, the server emits that information to the client.

Since 4 depends on 3, my understanding is that it needs to be captured in a callback to effect synchronous behavior. That gave me this:

io.on('connection', function(socket){
  socket.on('need data', function(msg) {
    getLinkBacks(msg, socket);
  });
});


var getLinkBacks = function(title, socket) {
  request.get(/* relevant url */, function(err, res, body) {
    socket.emit("data", body);
  });
};

None of the socket.io documentation talks about async methods and it feels pretty weird to be passing the socket, rather than a callback function, which would be more Node-y. Am I using poor technique or thinking about the problem wrong or is this the standard way to emit the response of an asynchronous method?

Note: I would have put this on Code Review, but they don't have a tag for Socket.IO, which made me think it would fit better here.

I agree with you, Node's style is passing a callback function, so I would rewrite this code as follows:

io.on('connection', function(socket){
  socket.on('need data', function(msg) {
    getLinkBacks(msg, function(content) {
      socket.emit("data", content);
    });
  });
});


var getLinkBacks = function(title, fn) {
  request.get(/* relevant url */, function(err, res, body) {
    fn(body);
  });
};

This will keep each part of your app isolated, and getLinkBacks function will not have to know about what socket is. This is of course a good programming practice. Besides you could reuse getLinkBacks function in other parts of your app, which are not connected with socket object.

P.S. I would recommend Robert Martin's "Clean Code: A Handbook of Agile Software Craftsmanship". He gives very valuable advises about how to structure your code to make it "clean".

Good luck!