whiskers75
whiskers75

Reputation: 197

node.js Redis GET

I'm trying to get a value from a Redis database. Code:

                                    callback(null, 'Please enter PIN.');
                                    read = db.get(cmd + ':pin');
                                    console.log(read);
                                    n = db.get(cmd + ':name');
                                    waitingType = 'pin';
                                    wait = 1;

However, when I console.log(read) I get true. Why don't I get the value of db.get(cmd + ':pin')?

Upvotes: 0

Views: 355

Answers (2)

cdanea
cdanea

Reputation: 468

Node is meant to use lambda functions to pass callbacks. Try passing the rest of your decisions as behaviors to various responses:

read = db.get(cmd + ':pin', function(result) {
    console.log(read);
    // like this
    // ... and so on
});

Also, you might want to look a bit further into Redis, you can retrieve all your fields at once. See HMGET. I think you can improve the structure of your stored data to better suit the application logic.

// for example:
// set like this, where id is some front stuff you know ahead of time, 
// like the expected username from a login form, that is expected to be unique
// you may concatenate and hash, just make this unique
db.hmset("authData:" + id, {id:'uniqID', pin:0666, name:'that guy'});

// get like this
db.hmget("authData:" + id, function(err, data) {
    console.log(['data will contain id, pin and name keys', data]);
});

//output:
/* [
    'data will contain id, pin and name keys', 
    {id:'uniqID', pin:0666, name:'that guy'}
    ]
*/

Upvotes: 2

Roest
Roest

Reputation: 818

db.get is asynchronous, so the db call isn't done yet when your program reaches the console.log( read )

Upvotes: 1

Related Questions