【问题标题】:Implement findBy method at node_redis but , it doesn't work在 node_redis 实现 findBy 方法,但是它不起作用
【发布时间】:2012-08-04 03:18:52
【问题描述】:

所有。我在 node_redis 模块中实现 findBy("name","password") ,遵循这个。

user.js

 // return user find by name and password.
 User.findBy = function(name,password){
  console.log("calllelelelelll");
  var res;
  db.lrange("users",0,-1,function(err,users){

    users.forEach(function(item){
      var u = JSON.parse(item);
      if ((u.name == name) && (u.password == password)){
        res =  u;
      }
    });
    console.log(res);
    return res;
  });

};

###app.js

User.findBy(user.name,user.password);

但是,User.findBy(user.name,user.password) 函数返回 undefined ,console.log(res) 被记录

喜欢{名称:“nobinobiru”,密码:“harashin0219”}

我想知道为什么 findBy 函数返回 res 未定义,但 console.log(res) 工作正常。请帮忙。

提前致谢。

【问题讨论】:

    标签: javascript node.js node-redis


    【解决方案1】:

    你正在从db.lrange 回调返回 res,它什么都不做。如果 lrange 函数不是异步的,那么您需要将 return 语句下移到回调之后,因此它实际上是来自 findBy() 的返回值。

    但是,如果db.lrange 函数是异步的(我猜它可能是异步的),那么您就无法从中获取值并传入调用函数。相反,任何想要在成功处理程序回调中使用它返回的值的东西都需要在回调函数中或从回调函数中调用。

    【讨论】:

    • 谢谢!你节省了我很多时间!
    猜你喜欢
    • 2021-11-28
    • 2019-10-05
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多