ashwintastic
ashwintastic

Reputation: 2312

async/await in node js with express?

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;
          })
      });
  }   
}

Upvotes: 3

Views: 534

Answers (2)

Vikash Dahiya
Vikash Dahiya

Reputation: 5801

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();

    }
}

Upvotes: 2

Tomalak
Tomalak

Reputation: 338128

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.

Upvotes: 2

Related Questions