MIDE11
MIDE11

Reputation: 3550

Node.js & Redis / hget synchronize

I wish to create a synchronize command of hget in node.js.

I wrote the following:

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"
 }

The problem is that in res1, I always gets true, while I set numbers to this field:

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

It also returns true if the key doesn't exists.

How can I perform this command?

Edit (here is the full code and why I use sync call):

   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;

Upvotes: 0

Views: 1331

Answers (2)

pius.huang
pius.huang

Reputation: 1

co + co-redis can run it synchronously

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"
  }
});

Upvotes: 0

Joachim Isaksson
Joachim Isaksson

Reputation: 181047

This part is problematic;

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

the call to hget does not return the value, it calls back to a given callback (which you omitted) when the value has been fetched;

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

...would print the value of your key.

Upvotes: 1

Related Questions