Reputation: 7011
Im trying to create a file 'users.js' where id like to manage all the redis accesses to the users data. In this file i have the next function, where i get the users ive saved in a list, to then load all of them from their keys:
exports.getUsers = function(){
var usrs;
client.lrange('users', 0, -1, function(err, rep){
client.mget(rep, function(e,r){
usrs = r;
});
});
return usrs;
};
I have another file 'admin.js' where i try to manage the routes for my administration panel. In this file I require the users.js file, and i call to the users.getUsers() function. I expect to get an array with the users objects, or at least the string with all of them. The problem is that it always returns 'undefined'.
As i understand it, what is happening is that i try to return the usrs variable before the mget finish with the callback. But i dont know how to solve that.
The question is... how can i make the return statement wait for mget? Is there any other way to organize the code and keep the DB accesses separated by fields?
Upvotes: 1
Views: 489
Reputation: 311975
You can't make getUsers
wait for the response before returning, so you need to have your function support a callback parameter that your function calls when the data is ready:
exports.getUsers = function(callback){
client.lrange('users', 0, -1, function(err, rep){
client.mget(rep, function(e,usrs){
callback(e,usrs);
});
});
};
Upvotes: 2