So I have this code
    User.prototype.save = function (fn){ //User is just an object
        var password = hashPassword(null, this.pswrd);
        var query=client.query('INSERT INTO myUser(usrnm,pswrd)VALUES($1,$2) ,[this.name,password], function(err, result) {
            if(err) {console.log(err)}
        });
        query.on("end", function (result) {client.end();});     
    }
and the hashPassword is
version 1
function hashPassword(salt,pass){
    var salt = salt?salt:new Buffer(crypto.randomBytes(128)).toString('hex');
    var pass = pass;
    var a=crypto.pbkdf2(pass, salt , 10000, 256, 'sha512',function(err, derivedKey) {
        return salt + (new Buffer(derivedKey).toString('hex')); 
    });
    return a;
}
I get a and password, undifined. I use return, so, why can just a take the value?
version 2
function hashPassword(salt,pass){
    var salt = salt?salt:new Buffer(crypto.randomBytes(128)).toString('hex');
    var pass = pass;
    crypto.pbkdf2(pass, salt , 10000, 256, 'sha512',function(err, derivedKey) {
        pass = salt + (new Buffer(derivedKey).toString('hex')); 
        console.log("pass in  > "+pass);
    });
    console.log("pass out  > "+pass);
    return pass;
}
I get pass in > fhjvoefvuhvuoedfv... (is hashed correctly), but pass out > undefined. Now, pass is global to hashPassword and I changed its value inside crypto, so why it does not keep it?
version 3
function hashPassword(salt,pass){
    var salt = salt?salt:new Buffer(crypto.randomBytes(128)).toString('hex');
    var pass = pass;
    var pass2;
    crypto.pbkdf2(pass, salt , 10000, 256, 'sha512',function(err, derivedKey) {
        pass2 = salt + (new Buffer(derivedKey).toString('hex'));    
        console.log("pass2 in  > "+pass2);
    });
    console.log("pass2 out  > "+pass2);
    return pass2;
}
So, I tried to fix the version2 problem by adding an extra var and I get pass2 in > fhjvoefvuhvuoedfv... (is hashed correctly), but pass2 out > undefined. How is this possible?
version 4
According to the first answer here I tried:
    var password ;
hashPassword(null, user.pswrd,function(p)
{
    password=p;
}
);
console.log("password  > "+password);
and
function hashPassword(salt,pass, fn){
    var salt = salt?salt:new Buffer(crypto.randomBytes(128)).toString('hex');
    var pass = pass;
    crypto.pbkdf2(pass, salt , 10000, 256, 'sha512',function(err, derivedKey) {
        fn(salt + (new Buffer(derivedKey).toString('hex')));    
    });
}
and password is undefined.
So, please, I tried and I tried and still nothing, please explain and show me what to do.
Thanks
 
     
    