1
var user =  db.User.find({ where: { username: username }}).then(function(user) {
      console.log("Authenticate"+user.authenticate(password));
      if (!user) {
        return null;
      } else if (!user.authenticate(password)) {
          return null;
      } else {
       return user;
      }
    }).catch(function(err){
      return err;
    });

I am Using Sequelize JS with Node JS. I want the object of the user that matches the where clause. but when I do return from then function . but it goes into infinite loop. I am new to Node Js and I don't know how to use Promise in Node Js. Please help mee

Terence Nero
  • 11
  • 1
  • 2

2 Answers2

1

The return value from db.User.find() is a promise. It will never be a user, so your first line is incorrect.

What you'll need to do is call the next function in your processing chain from within the promise then callback. This is the standard practice in Node.

If you return something from a then promise callback it's assumed to be another promise, which allows you to chain multiple promises in a row (example). That's not what you're looking for.

Your example would be better as something like:

function authentication(err, user){
  // Do something
}

db.User.find({ where: { username: username }}).then(function(user) {
      console.log("Authenticate"+user.authenticate(password));
      if (!user) {
        authentication(null, null);
      } else if (!user.authenticate(password)) {
          authentication(null, null);
      } else {
        authentication(null, user);
      }
    }).catch(function(err){
      authentication(null, user);
    });

Note the use of a callback to signify the result of your authentication test. Note also err as the first parameter to the callback, which is standard Node convention.

Community
  • 1
  • 1
srlm
  • 3,186
  • 2
  • 27
  • 40
0

Try to use try and catch block

Here is an example:

    authentication: async (req,res) => {

    try {

        let user = await User.findOne({
            where: {username: req.body.username}
        });

        user = user.toJSON();
        console.log(user);

       if (!user) {
               console.log('Not a user');
       }

  }

    catch (e) {

    console.log(e)

    }
}