agranig
agranig

Reputation: 129

Passing additional arguments down a callback chain in nodejs

I'm having difficulties in wrapping my mind around callbacks executed by predefined modules.

I've a socket.io client variable receiving an event, which should trigger a dns lookup of the given server, then send something to it. As far as I understood the whole concept, I execute the dns function, and in the callback execute another function which connects to my server, which in turn triggers another callback and so on, right? So my code looks like ths:

io.sockets.on('connection', function (client) { // comes from socket.io module
  client.on('myconnect', function (data) {
    doDns(client, data.server);
  });
}

var doDns = function (client, server) {
  client.emit('status', {m: 'going to resolve domain'});
  dns.resolve(server, 'A', doConnectToServer(???)); // comes from dns module
};

var doConnectToServer = function(???) {
  client.emit('status', {m: 'going to connect to server now'});
  // additional code goes here
}

So here is my problem: how do I pass my client variable down to the next callback, without losing what dns.resolve() will pass to the callback? When I change the line to this...

dns.resolve(server, 'A', doConnectToServer);

... then I have access to the dns results in the callback, but I lose my client variable, "console.log(arguments)" only shows the params passed down from the dns module, obviously. When I do it like this...

dns.resolve(server, 'A', doConnectToServer(client));

... then in my callback I'm missing the vars for the dns result. A "console.log(arguments)" in "doConnectToServer" function only shows the client variable.

So how am I supposed to tackle that?

And in general, am I on the completely wrong boat with my overall call flow (it's my first node.js app), or is this the way you'd design a node.js application?

Upvotes: 2

Views: 4964

Answers (1)

Ben Taber
Ben Taber

Reputation: 6751

You're close. Just pass the arguments along from within the doDNS function.

io.sockets.on('connection', function (client) { // comes from socket.io module
  client.on('myconnect', function (data) {
    doDns(client, data.server);
  });
}

var doDns = function (client, server) {
  client.emit('status', {m: 'going to resolve domain'});
  dns.resolve(server, 'A', function(err, addresses) {
    if (err) throw new Error(err);
    doConnecToServer(addresses, client);

  }); // comes from dns module
};

var doConnectToServer = function(addresses, client) {
  client.emit('status', {m: 'going to connect to server now'});
  // additional code goes here
}

Upvotes: 4

Related Questions