Home Async constructor via static function, but await doesn't work
Reply: 0

Async constructor via static function, but await doesn't work

user1370
1#
user1370 Published in May 20, 2018, 3:38 pm

I've created a simple user class with a username, hashedpassword and passwordsalt. Because the hashing and salting of takes some time, I decided to create a static async function to create a new user (Asynchronous constructor). But somehow when I call this static async function to create a new user, the await doesn't wait for the createUser to finish. Does anybody know why?

  console.log(1);
  var newUser = await User.createUser(newUserJson);
  console.log(3);
  console.log(newUser.getPasswordHash());  //<- this line fails with the error that it cannot do the .getPasswordHash on undefined.


static async createUser(jsonUser) {
    var password = jsonUser.password;
    const saltRounds = 10;
    try {
      bcrypt.genSalt(saltRounds, function(err, salt) {
        bcrypt.hash(password, salt, function(err, hash) {
          jsonUser.passwordHash = hash;
          jsonUser.passwordSalt = salt;

          var us = new User(jsonUser);  //nonblocking. Just sets some fields.
          console.log(2);
          return us;
        });
      })
    } catch (err) {
      console.log('error')
      console.log(err)
    }
  }

My console output shows 1, 3, 2...

Does anybody know why newUser.getPasswordHash() doesn't wait for var newUser = await User.createUser(newUserJson); ?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.341552 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO