Bdfy
Bdfy

Reputation: 24719

How to pass variable to callback function?

I have a simple example:

   for ( i in dbs ) {
       var db = dbs[i].split(':')
       var port = dbs[i][0]
       var host = dbs[i][0]
       var client = redis.createClient( port, host )
       tasks = [ [ "info" ] ]
       client.multi(tasks).exec(function (err, replies ) {
           console.log(port)
       })

How to print corrent port for each client connect ?

Upvotes: 0

Views: 99

Answers (1)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263137

A simple way is to enclose the loop body in a self-invoking anonymous function:

for (var i in dbs) {
    (function(i) {
        var db = dbs[i].split(":");
        var host = db[0];  // Probably 'db[0]' instead of 'dbs[i][0]'.
        var port = db[1];  // Probably 'db[1]' instead of 'dbs[i][0]'.
        var client = redis.createClient(port, host);
        tasks = [ [ "info" ] ];
        client.multi(tasks).exec(function(err, replies) {
            console.log(port);
        });
    })(i);
}

That way, the current value of port is properly captured by the closure and will be available in the callback passed to exec().

Note this answer assumes that dbs is an object, not an array, even though you're using i as the loop variable. If dbs is an array, you should use an indexed loop instead:

for (var i = 0; i < dbs.length; ++i) {
    // ...
}

Because for... in loops are not meant to iterate over arrays.

Upvotes: 5

Related Questions