I'm using the function below inside express js, but I can't return the value of pw.generate. Anyone knows why? I'm kinda new to JavaScript.
// create new xkcdPassword object
var pw = new xkcdPassword();
// set options for password generator
var options = {
numWords: 1,
minLength: 5,
maxLength: 8
};
var password = pw.generate(options, function(error, result) {
if(error){
return error;
}
// below variable now contains a password like "puppy"
var newPassword = result.join(' ');
// This does not work, somehow I cannot return the variable
return newPassword;
});
// below returns an undefined value
console.log(password);
So the variable "newPassword" does contain the password, inside pw.generate. I cannot use it outside pw.generate. Is it because the function which need to return the password, is used as a paramater?
EDIT: @scx gave me the solution for using a callback, because of the combination of the asynchronous and synchronous methods. I'm using a promise now as a callback, works great, this is my updated code:
function updatePassword(user) {
var deferred = Q.defer();
// create new xkcdPassword object
var pw = new xkcdPassword();
// set options for password generator
var options = {
numWords: 1,
minLength: 5,
maxLength: 8
};
var password = pw.generate(options, function(error, result) {
if(error){
return error;
}
var newPassword = result.join(' ');
user
.updateAttributes({
password: newPassword
})
.success(function(){
deferred.resolve(newPassword);
})
.error(function() {
deferred.reject();
});
})
return deferred.promise;
}
module.exports = {
passwordReset: function(req, res, next) {
updatePassword(user)
.then(function(password){
next();
}, function(){
// error
});
}
}