简体   繁体   中英

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 ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM