Ganesh Dagadi
Ganesh Dagadi

Reputation: 76

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

Upvotes: 1

Views: 38

Answers (3)

Alex G
Alex G

Reputation: 1917

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.

Upvotes: 2

Dhaval Darji
Dhaval Darji

Reputation: 513

I'm not sure but I think you should try this, try changing declaration of function like this. :

Just replace : with =

setSignedInUser = (cookie)=>{

}

Upvotes: 0

JustinMartinDev
JustinMartinDev

Reputation: 639

I think it's because you return the new promise inside your 2nd level promise.

Try to pass User.findOne in async like this:

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

Upvotes: 0

Related Questions