Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
          })
      });
  }   
}
like image 763
ashwintastic Avatar asked Dec 06 '25 00:12

ashwintastic


2 Answers

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.

like image 181
Tomalak Avatar answered Dec 07 '25 17:12

Tomalak


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

    }
}
like image 30
Vikash Dahiya Avatar answered Dec 07 '25 16:12

Vikash Dahiya