2012-08-07 41 views
0

我试图从Redis数据库获取值。代码:node.js Redis GET

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

然而,当我console.log(read)我得到true。为什么我没有得到db.get(cmd + ':pin')的价值?

回答

1

db.get方法是异步的,所以数据库调用不这样做然而,当你的程序达到的console.log(读)

+0

+1,但也增加了一个如何从cdanea使用的例子可能会有用的操作。 – Zlatko 2014-02-12 23:20:07

+0

只是说,ofcourse :) – Zlatko 2014-02-12 23:28:13

2

节点是指使用lambda函数传递回调。尝试通过你的决定的其余部分行为不同的反应:

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

此外,您可能希望进一步看起来有点成Redis的,你可以一次检索所有领域。请参阅HMGET。我认为您可以改进存储数据的结构以更好地适应应用程序逻辑。

// 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'} 
    ] 
*/