gpt4 book ai didi

node.js如何在中间件中从redis数据库中获取数据

转载 作者:可可西里 更新时间:2023-11-01 11:24:32 25 4
gpt4 key购买 nike

我正在做中间件模块,它将从 redis 中提取数据并放入 req.my_session。[此处]

这是在 app.use() 内部调用的函数;

  function parse_cookies(req){
if(req.headers.cookie != null){
var result = req.headers.cookie.match(new RegExp('m:[^=]*=[^; ]*', 'ig'));
if(result != null){
for(var i = 0; i < result.length; i++){
var result1 = result[i].split('=');
req.my_session[result1[0].substr(2)] = result1[1];
// get from redis value
client.get('sess:'+result1[1], function(err, reply) {
// reply is null when the key is missing
console.log(reply);
let li = i;
req.my_session[result1[0].substr(2)] = reply;
console.log('li = ' + li);
console.log('result1.lenght= ' + result.length);
if(i == result.length){
console.log('call the next');
}
});
}
}
}
} // parse_cookies

在控制台中,我总是输出 3,如何使用 redis.get 从数据库中获取所有数据,并在最后一次数据调用 next() 函数时从我的函数中退出?

problem it's get data from database in my middleware, I can't because redis has callback function

client.get("missingkey", function(err, reply) {
// reply is null when the key is missing
console.log(reply);
});

最佳答案

我认为问题是因为循环中的异步,您可以尝试以下操作

  function parse_cookies(req){
if(req.headers.cookie != null){
var result = req.headers.cookie.match(new RegExp('m:[^=]*=[^; ]*', 'ig'));
if(result != null){
var promises = [];
for(var i = 0; i < result.length; i++){
var result1 = result[i].split('=');
promises.push(getFromRd(req, result1));

}

return Promise.all(promises)
.then(() => {
return next()
})
.catch((e) => {
return next({error: e})
})
}
}
} // parse_cookies


function getFromRd(req, result1) {
req.my_session[result1[0].substr(2)] = result1[1];
// get from redis value
return client.get('sess:'+result1[1], function(err, reply) {
if (err) {
throw Error(' failed to find ' + 'sess:' + result1[1])
}
// reply is null when the key is missing
console.log(reply);
let li = i;
req.my_session[result1[0].substr(2)] = reply;
console.log('li = ' + li);
console.log('result1.lenght= ' + result.length);
return {success:true}
});
}

关于node.js如何在中间件中从redis数据库中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50917792/

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