title: How to pass a hashed password in a promise before posting it to the database using a Node.js server?
body: <p>On a node.js server I am using bcrypt to hash a password which is received by a user via a POST request and then store the hash in a database. The hashing function function takes longer to compute than creation of the saving of the hash and other parameters to the database, so I need to use a promise to executing the save after the hashing function has finished. I am using the Q library for this purpose, but I'm not sure how to do this. I am using mongoose for data modelling.</p>
  
  <h3>async bcrypt hashing function</h3>
  
  <pre><code>var bcrypt = require('bcrypt');
    bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(req.body.password, salt, function(err, hash) {
        // Store hash in DB
      });
    });
  });
  </code></pre>
  
  <h3>POST route</h3>
  
  <pre><code>app.post('/api/users', function(req, res) {
  
    var newUser = new User({
      email: req.body.email,
      name: req.body.name,
      password: hash
    });
  
    newUser.save(function(err) {
      if(!err) {
        return res.send({ status: 'User created' });
      } else {
        if(err.name == 'ValidationError') {
          res.statusCode = 400;
          res.send({ error: 'Bad Request' });
        } else {
          res.statusCode = 500;
          res.send({ error: 'Internal Server Error' });
        }
      } 
    });
  });
  </code></pre>
  
  <p>I would figure the population of the newUser variable and newUser.save() call would be the argument of then(), but how do I make the bcrypt hashing function issue the promise and pass the hash?</p>