无法在Node.js中的Redis中设置密钥

时间:2013-10-25 14:50:10

标签: node.js redis

我正在尝试在Node.js中使用Redis。我做错了什么......我无法理解它。

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

client.on("error", function (err) {
    console.log("error event - " + client.host + ":" + client.port + " - " + err);
});

/* first attempt */
console.log('first attempt');

var before = client.get("test");
console.log(before);

if(client.exists("test")) { 
    console.log("The value exists");
} else {
    console.log("The value doesn't exists");
    client.set("test","koen");
}

var after = client.get("test");
console.log(after);

/* second attempt */
console.log('--------------');
console.log('second attempt');

var before = client.get("test");
console.log(before);

if(client.exists("test")) { 
    console.log("The value exists");
} else {
    console.log("The value doesn't exists");
    client.set("test","koen");
}

var after = client.get("test");
console.log(after);

我无法设置任何键...控制台中显示以下内容:

first attempt
false
The value doesn't exists
false
--------------
second attempt
false
The value doesn't exists
false

2 个答案:

答案 0 :(得分:1)

client.set()不同步。您需要提供一个回调作为最后一个参数,此时您的密钥将被设置。

答案 1 :(得分:1)

以下是如何设置和获取“test”的示例:

client.set("test", "koen", function (err, res) {
  console.log("set: ", res)

  client.get("test", function (err, res) {
    console.log("get: ", res);
  });

});

请记住,所有通话都必须是异步的。