Node.js redis.lindex()返回的是true,而不是索引处的值

Node.js redis.lindex()返回的是true,而不是索引处的值,node.js,redis,node-redis,Node.js,Redis,Node Redis,我有一个现有的键值列表:键值1值2 在redis cli中运行LRANGE键0-1,返回: 1) value1 2) value2 这将确认键值列表存在。在redis cli中,运行LINDEX键0返回: "value1" 但是,在我的节点应用程序中,当我执行console.log(redis.lindex('key',0))时,它会打印true,而不是索引处的值 我做错了什么 注意:我使用的是节点redis包。对节点redis中的命令函数的调用是异步的,因此它们在回调中返回结果,而不是直接

我有一个现有的键值列表:
键值1值2

在redis cli中运行
LRANGE键0-1
,返回:

1) value1
2) value2
这将确认键值列表存在。在
redis cli
中,运行
LINDEX键0
返回:

"value1"
但是,在我的节点应用程序中,当我执行
console.log(redis.lindex('key',0))
时,它会打印
true
,而不是索引处的值

我做错了什么


注意:我使用的是
节点redis
包。

节点redis
中的命令函数的调用是异步的,因此它们在回调中返回结果,而不是直接从函数调用返回结果。您对
lindex
的调用应如下所示:

redis.lindex('key', 0, function(err, result) {
    if (err) {
        /* handle error */
    } else {
        console.log(result);
    }
});
function callLIndex(callback) {
    /* ... do stuff ... */

    redis.lindex('key', 0, function(err, result) {
        // If you need to process the result before "returning" it, do that here

        // Pass the result on to your callback
        callback(err, result)
    });
}
callLIndex(function(err, result) {
    // Use result here
});
如果您需要从所使用的任何函数中“返回”结果,则必须通过回调来实现。大概是这样的:

redis.lindex('key', 0, function(err, result) {
    if (err) {
        /* handle error */
    } else {
        console.log(result);
    }
});
function callLIndex(callback) {
    /* ... do stuff ... */

    redis.lindex('key', 0, function(err, result) {
        // If you need to process the result before "returning" it, do that here

        // Pass the result on to your callback
        callback(err, result)
    });
}
callLIndex(function(err, result) {
    // Use result here
});
你可以这样称呼它:

redis.lindex('key', 0, function(err, result) {
    if (err) {
        /* handle error */
    } else {
        console.log(result);
    }
});
function callLIndex(callback) {
    /* ... do stuff ... */

    redis.lindex('key', 0, function(err, result) {
        // If you need to process the result before "returning" it, do that here

        // Pass the result on to your callback
        callback(err, result)
    });
}
callLIndex(function(err, result) {
    // Use result here
});

所以我把代码改成了上面的代码。除了返回
result
而不是记录它,因为我是从不同的文件调用函数。它正在返回未定义的
。但是,当我记录它而不是返回它时,它记录得很好。为什么我可以记录它,但不能返回它?因为函数是异步的,所以不能从中返回。您需要做的是将回调传递给函数,然后从
redis.lindex
回调内部调用该回调。我将编辑我的答案来展示一个例子。