3

Hi I'm new in node js I'm using node version 7.10 to make apis

My controller

  class SomeControllerClass {

     async someFunction(req, req){
        var afterDBAction = await DbHelper.SomeOtherFunction(req.body)
         // afterDBAction is comming out undefined
     }

 }

I'm seperating DbHelper to make Controller thin and clean and all business logic is to be written at DbHelper.

User is the schema and its saving data in db but I dont't know why I'm getting undefined in my controller

class DbHelper {
  SomeOtherFunction(userinfo){
      var user = new User(userinfo);
      bcrypt.hash(userinfo.password, saltRounds).then(function(hash, err) { 
          user.password = hash;
          return user.save().then(function() {
              if (err)
                  return err;
              return user;
          })
      });
  }   
}
0

2 Answers 2

2

You forgot to return a value from your function. await expects a promise.

SomeOtherFunction(userinfo) {
    return bcrypt.hash(userinfo.password, saltRounds).then(function(hash, err) { 
        var user = new User(userinfo);
        user.password = hash;
        return user.save();
    });
}

Since the promise can fail for some reason, you need to use try/catch in your async function somewhere.

Sign up to request clarification or add additional context in comments.

2 Comments

now i'm getting Promise { <pending> } I think I have to resolve but don't know where??
Does user.save(); not resolve to the user object? What does it resolve to?
2

you can also write async function to make your code more clean

class DbHelper {
    async SomeOtherFunction(userinfo) {
        let hash = await bcrypt.hash(userinfo.password, saltRounds); 
        let user = new User(userinfo);
        user.password = hash;
        return user.save();

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.