简体   繁体   中英

Javascript object doesn't return a variable

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
    });
  }
}

According to this example you miss importing xkcd-password, try adding following before your code:

var xkcdPassword = require('xkcd-password');
var pw = new xkcdPassword();

Btw did you installed xkcd-password with npm correctly? If above will not help try installing with npm like bellow.

npm install xkcd-password

Update: Please check this answer and you will understand why you do not have access to that variable outside: How to return value from an asynchronous callback function?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM