简体   繁体   中英

Implement findBy method at node_redis but , it doesn't work

all. I implement findBy("name","password") at node_redis module, following this.

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

However,User.findBy(user.name,user.password) function return undefined , console.log(res) is logged

like {name: "nobinobiru",password: "harashin0219"}

I wonder why findBy function return res is undefined ,but console.log(res) is work correctly. Please help.

Thanks in advance.

You are returning res from the db.lrange callback which doesn't do anything. If the lrange function isn't asychronous, then you need to move the return statement down to after the callback so it's actually the return value from findBy() .

But, if the db.lrange function is asynchronous (which I'm guessing it might be), then you can't get values out of it and into the calling function. Instead, anything that wants to use the values returned by it into the success handler callback needs to be IN the callback function or called from the callback function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM