Search code examples
javascriptnode.jsexpresses6-promise

Not able to call promise that is returned from within a function


I have a function in the middleware file called setSignedInUser which receives a cookie as a parameter. I want to find a user saved in the SignedIn collection with the cookie,retrieve the user's unique id ,search for the user's complete information from the Users collection and return the foundUser which I would like to access in another file where the function is called from.

The middleware file:

const { resolve } = require('path');
const User = require('./Models/User'),
      SignedIn = require('./Models/SignedIn');

module.exports = {
   setSignedInUser : (cookie)=>{
      console.log(cookie)
    SignedIn.findOne({secretToken : cookie})
    .then(foundSignIn=>{
        userId = foundSignIn.userId;
        User.findOne({_id : userId})
        .then(foundUser=>{
            console.log(foundUser) // User is successfully found and loged to the console
            return new Promise((resolve , reject)=>{
                if(foundUser){
                    resolve(foundUser);
                }else{
                    reject('error')
                }
            })
        })
        .catch(err=>{
            console.log(err)
        })
    })
    .catch(err=>{
        console.log(err)
    })
  }
}

I call this function from the index.js file where my route is.

The index.js file:

const middleware = require('../middleware');
router.get('/' , (req , res)=>{
  middleware.setSignedInUser(req.cookies.auth_cook)
  .then(foundUser=>{
     console.log(foundUser)
  })
  .catch(err=>{
    console.log(err)
  })
 res.render('../views/general/home.ejs' , {user : user})
});

But here I get an error saying Cannot call .then on undefined

What am I missing here? Thankyou


Solution

  • You are not returning anything from your setSignedInUser function, so foundUser is undefined. A correct way would be this:

    module.exports = {
      setSignedInUser: (cookie) => {
        return new Promise((resolve, reject) => {
          SignedIn.findOne({
              secretToken: cookie
            })
            .then((foundSignIn) => {
              userId = foundSignIn.userId;
    
              User.findOne({
                  _id: userId
                })
                .then((foundUser) => {
                  if (foundUser) {
                    resolve(foundUser);
                  } else {
                    reject('error');
                  }
                })
                .catch((err) => {
                  console.log(err);
                  reject(err);
                });
            })
            .catch((err) => {
              console.log(err);
              reject(err);
            });
        });
      },
    };
    

    Since you want the result of an inner function you can return a Promise and resolve it with the inner value.