【问题标题】:Value from client.get() is "true" instead of the real valueclient.get() 的值是“真”而不是实际值
【发布时间】:2011-10-18 23:21:07
【问题描述】:

我正在使用 nowjs 和 node_redis。我正在尝试创建一些非常简单的东西。但到目前为止,本教程让我一片空白,因为他们只做 console.log()。

//REDIS
var redis = require("redis"),
    client = redis.createClient();

client.on("error", function (err) {
    console.log("Error "+ err);
});

client.set("card", "apple");

everyone.now.signalShowRedisCard = function() {
    nowjs.getGroup(this.now.room).now.receiveShowRedisCard(client.get("card").toString());
}

在我的客户端:

now.receiveShowRedisCard = function(card_id) {
    alert("redis card: "+card_id);
}

警报只给出“真”——我希望得到键“卡”的值,即“苹果”。

有什么想法吗?

【问题讨论】:

    标签: node.js redis nowjs-sockets


    【解决方案1】:

    也可以使用node_redis库提供的函数
    const getAsync = promisify(client.get).bind(client);
    并使用它从 redis 中获取值,如下所示
    const value = await getAsync(key)

    【讨论】:

      【解决方案2】:

      使用异步 Redis

      npm i async-redis --save

      const asyncRedis = require("async-redis");    
      const client = asyncRedis.createClient(); 
      
      await client.set("string key", "string val");
      const value = await client.get("string key");
      
      console.log(value);
      
      await client.flushall("string key");
      

      【讨论】:

        【解决方案3】:

        一种选择是使用 Bluebird 将 Redis 回调转换为 Promise。然后您可以将其与.then()async/await 一起使用。

        import redis from 'redis'
        import bluebird from 'bluebird'
        
        bluebird.promisifyAll(redis)
        const client = redis.createClient()
        
        await client.set("myKey", "my value")
        const value = await client.getAsync("myKey")
        

        请注意,您的方法应该有 Async 附加到它们。

        【讨论】:

        • 可以将客户端导出到其他模块使用吗?我正在尝试导出它,但它仍然返回 true 进行查询。
        【解决方案4】:

        您正在尝试以同步方式使用异步库。这是正确的方法:

        //REDIS
        var redis = require("redis"),
            client = redis.createClient();
        
        client.on("error", function (err) {
            console.log("Error "+ err);
        });
        
        client.set("card", "apple", function(err) {
            if (err) throw err;
        });
        
        everyone.now.signalShowRedisCard = function() {
            var self = this;
            client.get("card", function (err, res) {
                nowjs.getGroup(self.now.room).now.receiveShowRedisCard(res);
            });
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-02-09
          • 2021-10-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-14
          • 1970-01-01
          相关资源
          最近更新 更多