AG_HIHI
AG_HIHI

Reputation: 1995

Why isn't the promise being passed on to the next then?

I am trying to determin whether the role of an admin in my app is a super user or not through this code:

AdminServices.js

var isSuper_User = function(email) {
  models.admin.findOne({ where: { email } }).then(function(admin) {
    logger.debug("Fetching user with email: ", email);
    logger.debug("admin.role: ", admin.role);
    isSuper_User = admin.role === 'super_user' ? true : false;
    logger.debug("isSuper_User: ", isSuper_User);
    new Promise(function(resolve, reject) {
      resolve(isSuper_User)
    })
  }).catch(err=> 
    logger.debug(err.toString())
    );
};

admin_routes.js

router.get("/isSuperUser/:email", function(req, res) {
  logger.debug("req.params.email: ", req.params.email);


 adminService.isSuper_User(req.params.email).then(isSuper_User => {
    logger.info("isSuper_User returned from promise: ", isSuper_User);
  });

});

logger is a module that allows to customize the logging in the terminal.
However when I send the request with an email, for a user whose role is an admin the logger code inside admin_routes doesn't log anything. Everything inside AdminServices works perfectly though.
This is what I get in the terminal :
enter image description here
So the problem is with the way I handled the promise. But, I do not see what I've done wrong exactly.

Upvotes: 0

Views: 69

Answers (3)

Sohail Ashraf
Sohail Ashraf

Reputation: 10579

You have to return the promise from the function. In the given code you are not returning anything, which is equal to undefined.

var isSuper_User = function(email) {
  return models.admin
    .findOne({ where: { email } })
    .then(function(admin) {
      logger.debug("Fetching user with email: ", email);
      logger.debug("admin.role: ", admin.role);
      isSuper_User = admin.role === "super_user" ? true : false;
      logger.debug("isSuper_User: ", isSuper_User);
      return isSuper_User;
    })
    .catch(err => {
      logger.debug(err.toString());
      throw err;
    });
};


Upvotes: 2

arizafar
arizafar

Reputation: 3122

Function isSuper_User is not returning anything.

Function should return the promise

var isSuper_User = function(email) {
  return models.admin.findOne({ where: { email } }).then(function(admin) {
    logger.debug("Fetching user with email: ", email);
    logger.debug("admin.role: ", admin.role);
    isSuper_User = admin.role === 'super_user';
    //admin.role === 'super_user' already returns true or false so no need of ternary.
    logger.debug("isSuper_User: ", isSuper_User);
    return isSuper_User;
    //No need of promise wrapper here.
  }).catch(err=> 
    logger.debug(err.toString())
    );
};

Upvotes: 2

Quentin
Quentin

Reputation: 943601

The isSuper_User function has no return statement.

It doesn't return a promise, it returns undefined.

You need to explicitly return the promise.

return models.admin.findOne....

Upvotes: 0

Related Questions