方法未定义?不能使用 yield

Method undefined? Cannot use yield

我想产生一个过程。但是,我收到错误消息:You may only yield a function, promise, generator, array, or object, but the following object was passed: "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 没有 return 任何东西,这就是为什么你会得到一个关于它产生 undefined.

的错误

假设您想要 comparePassword 到 return 一个承诺。这意味着你需要用一个承诺包装 bcrypt.compare()——它使用回调——并且 return 这个承诺:

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