我是nodejs的新手。我的要求是从其余表中保存一些用户详细信息,以便在我的rest api项目中进行进一步处理,在阅读后,我应该保存会话中查询的结果以供进一步使用。这是我的代码,我无法在查询结果异步调用之外获取会话值。 保存来自不同表的用户详细信息并将其用于进一步查询的最佳方法是什么。
方法:
if(sess.email)
{
console.log("session is valid");
checkProfile.getRightOnCity(req.decoded , req.session);
console.log("city session ::" , sess.cities); //i am getting this undeifned
}
getRightOnCity:
var getRightOnCity = function getRightOnCity(req_decoded,req_session) {
var myPromise = dbname(req_decoded);
var user_id = getUserid(req_decoded);
var details = getUserDetails(req_decoded);
console.log("user details :: " , details);
var cities = [];
myPromise.then(function(myDBName) {
new_conn(myDBName).query("Select city_id from " + myDBName + ".rights_on_city where user_id="+user_id, function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else{
for(var i=0 ; i < res.length ; i++) {
cities.push(res[i].city_id);
req_session.cities = cities.join();
console.log("city::" , req_session.cities);
console.log("email inside get cities " , req_session.email);
req_session.save();
}
}
});
});
};
答案 0 :(得分:2)
首先,您需要从getRightOnCity
函数返回诺言。
return myPromise.then
可能还需要将DB调用包装在promise中。
function getRightOnCity(req_decoded, req_session) {
var myPromise = dbname(req_decoded);
var user_id = getUserid(req_decoded);
var details = getUserDetails(req_decoded);
console.log("user details :: ", details);
var cities = [];
return myPromise
.then(function (myDBName) {
return new Promise((resolve, rej)=>{ //<==here
new_conn(myDBName).query("Select city_id from " + myDBName + ".rights_on_city where user_id=" + user_id, function (err, res) {
if (err) {
console.log("error: ", err);
result(null, err);
rej(err);
} else {
for (var i = 0; i < res.length; i++) {
cities.push(res[i].city_id);
req_session.cities = cities.join();
console.log("city::", req_session.cities);
console.log("email inside get cities ", req_session.email);
req_session.save();
}
resolve();
}
});
})
});
};
现在,要使用它,您需要.then
或await
函数。
if (sess.email) {
console.log("session is valid");
checkProfile
.getRightOnCity(req.decoded, req.session)
.then(()=>{
console.log("city session ::", sess.cities);
})
}
注意:混合使用Promise
和callback
答案 1 :(得分:-1)
当您将req.session
传递给getRightOnCity
到req_session
时,只是传递了req.session
内容的副本。您应该直接从第一种方法或通过ExpressJS中间件函数来操作req.session
。