req.sessionStore.all wait无法在带有mongoDB的node.js中工作



/* 🙅 current working */
export const userProfile = async (req, res) => {
const loggedInUserList = [];
const {
params: { id }
} = req;
// await not working..
await req.sessionStore.all((error, sessions) => {
sessions.forEach((session) => {
loggedInUserList.push(session.user._id);
console.log("I want first", loggedInUserList);
console.log(loggedInUserList.includes(id));
});
});
console.log("I want second", loggedInUserList);
const isUserLogin = Boolean(loggedInUserList.includes(String(id)));
console.log("I want third", isUserLogin);
const user = await User.findById(id)
.populate("boards")
.populate("followUsers")
.populate("followingUsers");
return res.status(200).render("user-profile", { user });
};

我想从req.sessionStore中获取会话,在检查拥有req.params.id的用户是否通过会话中的if用户id登录。但等待不起作用。。这是的结果

I want second []  
I want third false  
I want first ['6241c87a3e95f193789c9ae0'] <- this is user id  
true

(⬇️我想要这样的结果。(

I want first ['6241c87a3e95f193789c9ae0']  
true  
I want second ['6241c87a3e95f193789c9ae0']  
I want third true

为了得到这样的结果,我试着等待。但仍然不起作用。。。

永远不要同时使用基于承诺的方法和基于回调的方法。也就是说,要么使用基于async await/promise的方法,要么使用回调函数。

由于您使用的是异步函数,因此使用await是最合适的。您的正确代码是:

const sessions = await req.sessionStore.all();
sessions.forEach((session) => {
loggedInUserList.push(session.user._id);
console.log('I want first', loggedInUserList);
console.log(loggedInUserList.includes(id));
});

最新更新