safaiyeh safaiyeh - 1 year ago 80
Node.js Question

Method undefined? Cannot use yield

I want to yield a process. However, I get the error: You may only yield a function, promise, generator, array, or object, but the following object was passed: "undefined".

Not sure why.

Mongoose method:

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


Usage:

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


The error occurs when in usage. user is not null or undefined.

Answer Source

The problem is that comparePassword doesn't return anything, that's why you get an error about it yielding undefined.

Let's assume that you want comparePassword to return a promise. That means that you need to wrap bcrypt.compare()—which uses callbacks—with a promise, and return that promise:

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

This is how you'd use it:

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