NodeJS将variables传递给已定义的callback函数

考虑下面的代码:

if(connections.hasOwnProperty(id)){ console.log('client '+id+' is connected. querying redis.'); id = id; redisClientActor.lrange("NOTIFICATIONS_"+id, 0, 0, function(err, reply) { if(reply !== null && reply !== undefined){ console.log(JSON.stringify(Object.keys(connections))); connections[id].sendUTF(reply); console.log('Forwarded notification to client '+id); }else{ console.log(err); } }); }else{ console.log('Received notification, but client '+id+' not connected.') } 

它是用NodeJS编写的非常基本的通知服务器的一部分。 它使用redis npm软件包。 由于节点的asynchronous特性,我明白为什么代码目前无法工作( id超出范围,导致sendUTF失败,导致脚本崩溃)。

如果lrange是一个自定义的函数,那么我只需在这里添加第三个参数,并完成它。 但是,因为我不是很难find如何访问lrangecallback(l5及以下)中的“id”

我会非常感激一个正确的方向提示。

如果你通过一个改变“id”值的循环进行迭代,callback函数将会看到最后一次迭代中分配给它的“id”的最后一个值。

在这种情况下,您需要使用闭包来捕获id的值:

 var produceClosureForId = function(id){ return function(err, reply) { if(reply !== null && reply !== undefined){ console.log(JSON.stringify(Object.keys(connections))); connections[id].sendUTF(reply); console.log('Forwarded notification to client '+id); }else{ console.log(err); } }; } redisClientActor.lrange("NOTIFICATIONS_"+id, 0, 0, produceClosureForId(id) );