简体   繁体   English

如何将变量传递给回调函数?

[英]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() . 这样, port的当前值将由闭包正确捕获,并将在传递给exec()的回调中使用。

Note this answer assumes that dbs is an object, not an array, even though you're using i as the loop variable. 请注意,即使您将i用作循环变量,该答案也假定dbs是一个对象,而不是数组。 If dbs is an array, you should use an indexed loop instead: 如果dbs是一个数组,则应改用索引循环:

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

Because for... in loops are not meant to iterate over arrays . 因为for... in循环并不意味着要在array上进行迭代

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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