gpt4 book ai didi

node.js - Redis node.js - 链接调用以获取用户数据

转载 作者:可可西里 更新时间:2023-11-01 11:13:52 27 4
gpt4 key购买 nike

我有一个用户数据库:配置文件、产品、配置以及用户可能拥有的其他内容。我正在尝试找出一种方法来成功地链接我的 redis 调用(一个“getAll”函数),以便我可以返回一个包含所有这些东西的对象,例如:

user = {
profile: {},
products: {},
config: {},
...
}

这是我访问它们的方式/我正在尝试做的事情:

User.getAll = function(uid, next){

var user = {};
var multi = client.multi();

var key = 'user' + uid;
client.hgetall(key, function(err, profile){
user.profile = profile;
//signal that profile is ready
}

key = 'products:' + uid;
client.smembers(key, function(err, arr){
key = key + ':';
for (i=0; i < arr.length; i++){
multi.hgetall(key + arr[i]);
}
multi.exec(function(err, products){
user.products = products;
//signal that products is ready
}));
})

if (ready) { //obviously this isn't correct.
return next(null, user);
}
}

收到所有我想要的数据后,我该如何继续?事件发射器是正确的方法吗?

最佳答案

我认为事件发射器在这里不是一个好的选择。你可以跟踪所有的电话,像这样:

User.getAll = function(uid, next){
var requests = ["first", "second"];
var check_request = function(_key) {
var idx = requests.indexOf(_key);
if (idx!==-1) {
requests.splice(idx, 1);
}
if (!requests.length) {
next(user);
}
};

// ORIGINAL CODE + check_request
var user = {};
var multi = client.multi();

var key = 'user' + uid;
client.hgetall(key, function(err, profile){
user.profile = profile;
check_request("first");
}

key = 'products:' + uid;
client.smembers(key, function(err, arr){
key = key + ':';
for (i=0; i < arr.length; i++){
multi.hgetall(key + arr[i])
}
multi.exec(function(err, products){
user.products = products;
check_request("second");
}));
})
}

显然,您将使用比 requests = ["first", "second"]; 更有意义的东西,但我希望您明白这一点。

另请查看 async.js .这是一个很好的库,可以为您简化这些,并且可以做更多的事情。

关于node.js - Redis node.js - 链接调用以获取用户数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15866568/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com