Master AgentX
Master AgentX

Reputation: 395

Unable to use variable outside the function

I am using Koa module - Node js and mysql & stuck on a problem.

In signup function (inside welcomeCtrl.js) I have:

var bcrypt = require('bcrypt');
module.exports = {
signup: function* (next) {
 bcrypt.genSalt(10, function(err, salt) {
        console.log(salt);
        bcrypt.hash(password, salt, function(err, hash) {
            // Store hash in your password DB. 
            console.log(hash); //no error
            var hashedPassword = hash;
        });
       });
        console.log(bcrypt.hash.hash); //gives error
             //or
        console.log(bcrypt.hash.hahedPassword); //gives error

        queryString = "insert into user(email,name, phone, password, course_id, dpt_id) values('%s','%s','%s','%s','%s','%s')";
        query = util.format(queryString, email, name, phone, hash, courseId, dptId);
        results = yield databaseUtils.executeQuery(query);
        this.redirect('/');
    }
   }

I am calling signup post function in different routes.js file as:

router.post('/signup', welcomeCtrl.signup);

Here is the executeQuery function in the databaseUtils.js file

 var executeQuery = function(query, callback) {
 pool.getConnection(function(err, connection) {
    // Use the connection
    connection.query(query, function(err, rows, fields) {
        connection.release();
        if(err) {
            err.mysqlQuery = query;
            logger.logError(err);
        }

        if(typeof callback == "function") {
            callback(err, rows);
        }
        // Don't use the connection here, it has been returned to the pool.
    });
});
};
 module.exports = {
executeQuery: thunkify(executeQuery),
executePlainQuery: executeQuery
};

Is there any way to use hash variable outside the function so that it can be inserted in query?

Upvotes: 1

Views: 252

Answers (1)

Dave Irvine
Dave Irvine

Reputation: 416

You should move your query function into the callback for bcrypt.hash.

bcrypt.genSalt(10, function(err, salt) {
      console.log(salt);

      bcrypt.hash(password, salt, function(err, hash) {
        // Store hash in your password DB. 
        console.log(hash); //no error
        queryString = "insert into user(email,name, phone, password, course_id, dpt_id) values('%s','%s','%s','%s','%s','%s')";
        query = util.format(queryString, email, name, phone, hash, courseId, dptId);

        databaseUtils.executeQuery(query, function() {
          this.redirect('/');
        });
      });
    });

Problem is, where does your redirect function come from? You're going to loose context on this unless you bind the functions. Do fat arrow functions work in your setup? If so you could do it that way.

Upvotes: 1

Related Questions