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

Mun*_*med 3 redis node.js node-redis

我有一个现有的键值列表:key value1 value2.

redis-cli,我跑LRANGE key 0 -1,返回:

1) value1
2) value2
Run Code Online (Sandbox Code Playgroud)

这确认了键值列表存在.在redis-cli,运行LINDEX key 0返回:

"value1"
Run Code Online (Sandbox Code Playgroud)

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

我究竟做错了什么?

注意:我正在使用该node-redis包.

Mik*_*e S 8

对命令函数的调用node-redis是异步的,因此它们在回调中返回结果,而不是直接从函数调用返回.你的电话lindex应该是这样的:

redis.lindex('key', 0, function(err, result) {
    if (err) {
        /* handle error */
    } else {
        console.log(result);
    }
});
Run Code Online (Sandbox Code Playgroud)

如果你需要从你所处的任何函数"返回"结果,你必须通过回调来做到这一点.像这样的东西:

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)
    });
}
Run Code Online (Sandbox Code Playgroud)

您可以这样称呼:

callLIndex(function(err, result) {
    // Use result here
});
Run Code Online (Sandbox Code Playgroud)