开发者

Using redis and node.js issue: why does redis.get return false?

I'm running a simple web app backed by node.js, and I'm trying to use redis to store some key-value pairs. All I do is run "node index.js" on the command line, and here's the first few lines of my index.js:

var app = require('express').createServer();
var io = require('socket.io').listen(app);

var redis = require('redis');
var redis_client = redis.createClient();
redis_client.set("hello", "world");
console.log(redis_client.get("hello"));

However, all I get for redis_client.get("hello") instead of "world" is false. Why is it not returning "world"?

(And I am running the redis-server)

What's weird too is that the example code posted here runs fine, and produces the expected 开发者_Go百科output. Is there something I'm doing incorrectly for simple set and get?


i could bet get is asynchronous, so you would get the value by callback.

Edit:
It's really asynchronous: file.js


Here you go! For ES6

redis_client.get("hello", (err, data)=>{
  if(err){
    throw err;
  }
  console.log(data);
});

For ES5

redis_client.get("hello", function(err, data){
  if(err){
    throw err;
  }
  console.log(data);
});


This might help someone who hates using callbacks:

Just promisify it without having to use external library by doing something like:

new Promise((resolve, reject) => {
  redis_client.get("hello", (e, data) => {
    if(e){
      reject(e);
    }
    resolve(data);
  });
});


Nowadays, Redis uses a promises API.

const redis = require("redis"); // 4.0.1
const redisClient = redis.createClient();

(async () => {
  await redisClient.connect();
  await redisClient.set("hello", "world");
  console.log(await redisClient.get("hello")); // => world
  await redisClient.quit();
})();


Had the same issue, solved it by using promisify.

const redis = require('redis');
const util = require('util');
const redisUrl ="redis://127.0.0.1:6379";
const client = redis.createClient(redisUrl);

client.set = util.promisify(client.set)

client.get = util.promisify(client.get);


const setRed =async ()=>{
    await client.set('name','Jo');
    let name = await client.get('name');
//prints the value for name
    console.log(name);
}

setRed();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜