繁体   English   中英

NodeJS / MongoDB。 异步/等待返回整个数据数组

[英]NodeJS/MongoDB. Async/await returns the whole array of data

因此,我试图理解为什么在MongoDB的情况下Async / await返回一些奇怪的结果,而不是受条件的束缚?

例如:我试图让req.session.userIdawait User.find()但总是得到用户的阵列。

我的代码:

.get((req, res) => {
        let a = '';
        async function userFind() {
            const sess = await User.find((err, users) => {
                if (req.session.userId !== undefined) {
                    return req.session.userId; // return the all array ou Users, instead of just session value
                } 
                else {
                    return "req.session.userId"; // return the all array of Users, instead of just a string
                }
            });
            console.log(sess);

            const empl =  await EmployersSchemaDB.find((err, employers) => {
                return employers; 
            });

            return {
                sess, 
                empl
            }
        }   
        console.log(userFind()); // gives two arrays of data above together, but not that I want...
})

您必须await userFind()函数。

异步功能的工作方式是它们返回承诺。 您正在等待userFind()内部的数据库访问,但不是在等待userFind()本身。

.get(async (req, res) => {
        let a = '';
        async function userFind() {
            const sess = await User.find((err, users) => {
                if (req.session.userId !== undefined) {
                    return req.session.userId; // return the all array ou Users, instead of just session value
                } 
                else {
                    return "req.session.userId"; // return the all array of Users, instead of just a string
                }
            });
            console.log(sess);

            const empl =  await EmployersSchemaDB.find((err, employers) => {
                return employers; 
            });

            return {
                sess, 
                empl
            }
        }   
        console.log(await userFind()); // gives two arrays of data above together, but not that I want...
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM