22

I am using nowjs and node_redis. I am trying to create something very simple. But so far, the tutorial have left me blank because they only do 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());
}

In my client side:

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

The alert only gives out "true" - I was expecting to get the value of the key "card" which is "apple".

Any ideas?

wenbert
  • 5,263
  • 8
  • 48
  • 77

4 Answers4

18

You are trying to use an async library in a sync way. This is the right way:

//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);
    });
}
stagas
  • 4,607
  • 3
  • 28
  • 28
8

One option is to use Bluebird to turn Redis callbacks into promises. Then you can use it with .then() or 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")

Notice your methods should have Async appened to them.

crash springfield
  • 1,072
  • 7
  • 17
  • 33
  • Can you export the client to another module for use? I am trying to export it and it still returns `true` for queries. – Mark A Jul 06 '19 at 20:24
4

Use Async 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");
bereket gebredingle
  • 12,064
  • 3
  • 36
  • 47
1

You can also use a function provided by node_redis library
const getAsync = promisify(client.get).bind(client);
and use this to get values from redis as follows
const value = await getAsync(key)

Tejas
  • 61
  • 4