函数不返回数据

时间:2011-06-02 13:03:28

标签: node.js redis serverside-javascript

我有以下代码

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

var getuser = function(username) {
  var userhash={};
  client.hgetall("users."+username, function(err, user) {
    userhash=user;
  });
  return userhash;
};
user_rahul = { 
     username: 'rahul',
     queueno: 1,
     sessionId: '6604353811126202'

   };
user_namita = {
  username: 'namita',
  sessionId:'2'
};
client.hmset('users.rahul', user_rahul);
client.hmset('users.namita', user_namita);
var username = "rahul"; // From a POST perhaps
  var user1=getuser(username);
  console.log(user1);
client.hgetall("users." + username, function(err, user) {
  console.log(user);

});

我创建了一个getuser函数来返回userhash中特定用户名的值,但它没有返回请帮助找到它没有返回的原因。 我该怎么办才能获得价值回报?

1 个答案:

答案 0 :(得分:2)

当您在同步getUser函数中进行异步调用时,您正在混合同步和异步模式。您需要使getUser函数异步 - 例如:

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

var getuser = function(username, cb) {
  client.hgetall("users."+username, cb);
};

user_rahul = { 
     username: 'rahul',
     queueno: 1,
     sessionId: '6604353811126202'

   };
user_namita = {
  username: 'namita',
  sessionId:'2'
};

client.hmset('users.rahul', user_rahul);
client.hmset('users.namita', user_namita);
var username = "rahul"; // From a POST perhaps
getuser(username, function(err, res){
     console.log(res);
 });
client.hgetall("users." + username, function(err, user) {
  console.log(user);
});