我有一个简单的例子:
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)
})
如何为每个客户端连接打印相应的端口?
最佳答案
一种简单的方法是将循环主体包含在一个自调用匿名函数中:
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);
}
这样,
port
的当前值将由闭包正确捕获,并将在传递给exec()
的回调中使用。请注意,即使您将
dbs
用作循环变量,该答案仍假定i
是对象而不是数组。如果dbs
是数组,则应改用索引循环:for (var i = 0; i < dbs.length; ++i) {
// ...
}
因为
for... in
循环are not meant to iterate over arrays。