NodeJS将变量传递给已定义的回调函数

NodeJS passing variable to already defined callback function

本文关键字:定义 回调 函数 变量 NodeJS      更新时间:2023-09-26

考虑以下代码:

    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编写的非常基本的通知服务器的一部分。它使用redisnpm包。由于Node的异步性质,我理解代码当前无法工作的原因(id超出范围,导致sendUTF失败,导致脚本崩溃)。

如果lrange是一个自定义函数,我只需在这里添加第三个参数并完成它。但由于不是这样,我很难找到如何访问lrange回调(l5及以下)内部的"id"的解决方案

如果能给我一个正确方向的快速提示,我将不胜感激。

如果您正在通过一个改变"id"值的循环进行迭代,则回调都会看到上次迭代期间分配给它的"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) );