Node.js 方法未定义?不能使用收益率

Node.js 方法未定义?不能使用收益率,node.js,mongoose,bcrypt,Node.js,Mongoose,Bcrypt,我想产生一个过程。但是,我得到了一个错误:您可能只生成一个函数、承诺、生成器、数组或对象,但传递了以下对象:“undefined” 不知道为什么 猫鼬法: UserSchema.methods.comparePassword = function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err){ retur

我想产生一个过程。但是,我得到了一个错误:您可能只生成一个函数、承诺、生成器、数组或对象,但传递了以下对象:“undefined”

不知道为什么

猫鼬法:

UserSchema.methods.comparePassword = function(candidatePassword, cb) {
 bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
    if (err){
       return cb(err);
     }
    cb(null, isMatch);
 });
};
用法:

yield user.comparePassword(this.request.body.password, function(err, isMatch) {
    console.log(isMatch);
});

该错误在使用时发生。用户不是空的或未定义的。

问题是
comparePassword
不返回任何内容,这就是为什么您会得到一个错误,导致
未定义的

假设您希望
comparePassword
返回承诺。这意味着您需要包装
bcrypt.compare()
——它使用带承诺的回调,并返回该承诺:

UserSchema.methods.comparePassword = function(candidatePassword) {
  var user = this;
  return new Promise(function(resolve, reject) {
    bcrypt.compare(candidatePassword, user.password, function(err, isMatch) {
      if (err) return reject(err);
      resolve(isMatch);
    });
  });
};
以下是您使用它的方式:

yield user.comparePassword(this.request.body.password); // no callback

问题是,
comparePassword
没有返回任何内容,这就是为什么您会得到一个关于它的错误,从而产生
未定义的

假设您希望
comparePassword
返回承诺。这意味着您需要包装
bcrypt.compare()
——它使用带承诺的回调,并返回该承诺:

UserSchema.methods.comparePassword = function(candidatePassword) {
  var user = this;
  return new Promise(function(resolve, reject) {
    bcrypt.compare(candidatePassword, user.password, function(err, isMatch) {
      if (err) return reject(err);
      resolve(isMatch);
    });
  });
};
以下是您使用它的方式:

yield user.comparePassword(this.request.body.password); // no callback