Node.js& Redis / hget同步

时间:2016-02-21 13:26:33

标签: node.js redis

我希望在node.js中创建hget的同步命令。

我写了以下内容:

var db = require("redis");
var dbclient = db.createClient();
var res1 = dbclient.hget("all_records", "/" + full_path)
if (res1 != undefined){
    objStatus.status = "TRUE"
 } else {
     objStatus.status = "FALSE"
 }

问题在于res1,我总是得到true,而我在这个字段中设置了数字:

dbclient.hset("all_records", key, size); // size is number

如果密钥不存在,它也会返回true。

我该如何执行此命令?

编辑(这是完整代码以及我使用同步调用的原因):

   for (var attr in paths) {
        var full_path = "/0" + attr
        var objStatus = new Object();
        var res1 = dbclient.hget("all_records", "/" + full_path)
        if (res1 != undefined){
            objStatus.status = "TRUE"
        } else {
            objStatus.status = "FALSE"
        }
     }
     arrayResult.push(objStatus);
    }
    return arrayResult;

2 个答案:

答案 0 :(得分:1)

这部分有问题;

var res1 = dbclient.hget("all_records", "/" + full_path)

hget的调用不返回值,它在获取值时回调给定的回调(你省略了);

dbclient.hget("all_records", "/" + full_path, function(err, res) {
  console.log(res);
});

...会打印钥匙的价值。

答案 1 :(得分:0)

co + co-redis可以同步运行

var co = require('co');
var redisClient = require('redis').createClient();
var wrapper = require('co-redis');
var redisCo = wrapper(redisClient);
co(function* () {
  var res1 = yield redisCo.hget("all_records", "/" + full_path)
  if (res1 != undefined){
     objStatus.status = "TRUE"
  } else {
     objStatus.status = "FALSE"
  }
});