Implement findBy method at node_redis but , it doesn't work
-
24-06-2021 - |
Question
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.
La solution
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.