【问题标题】:redis.lindex() is returning true rather than the value at the indexredis.lindex() 返回 true 而不是索引处的值
【发布时间】:2014-10-09 16:18:57
【问题描述】:

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

redis-cli 中,我运行LRANGE key 0 -1,它返回:

1) value1
2) value2

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

"value1"

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

我做错了什么?

注意:我使用的是node-redis 包。

【问题讨论】:

    标签: node.js redis node-redis


    【解决方案1】:

    node-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
    });
    

    【讨论】:

    • 所以我将代码更改为您上面的代码。除了我返回result 而不是记录它,因为我从不同的文件调用该函数。它正在返回undefined。但是,当我记录它而不是返回它时,它记录得很好。为什么我可以登录,但不能返回?
    • 由于该函数是异步的,因此您不能从中return。您需要做的是向您的函数传递一个回调,然后从redis.lindex 回调中调用该回调。我将编辑我的答案以显示一个示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    相关资源
    最近更新 更多