简体   繁体   中英

passing variable to next middleware in req in express.js

I am trying to pass variable to the next middlewares through the req object. getting some data from database and passing that data to request for next middlewares to use.

User.findone({ _id: someId })
    .then(user => { req.user = user })
    .catch(err => {  })

After that then and catch block i am using next() . Therefore for the next middlewares i am getting req.user undefined. but if i pass the next() function in the then block after req.user = user like .then(user=> {req.user = user; next()}) than i am getting req.user a valid user object to use for the next middlewares. what is the reason for this behaviour??

That's because the User.findOne function is asynchronous. The result of that function is only known in the then block.

const middleware = (req, res, next) => {
    User.findOne({ _id: someId })
        .then(user => {
            req.user = user;
        })
        .catch(err => { });
    next(); // If you put next() here, the request will go straight to the next middleware without waiting for User.findOne() to complete.
};
const middleware = (req, res, next) => {
    User.findOne({ _id: someId })
        .then(user => {
            req.user = user;
            next(); // Putting next() here is correct
        })
        .catch(err => {
            next(err); // Remember to handle error to avoid hanging the request
        });
};

then... is called after the User.findone promise resolves. Thus, if you put next() outside of then , it will be called before then .

You could read more details at promise-basics

Alternatively try to use async-await as it looks more straightforward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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