6

我是 Promises 的新手,不知道如何解决这个问题:我正在做一个身份验证系统,我的第一个电话是检查数据库上的电子邮件。如果用户存在,则根据 bcrypted 密码检查密码......我正在使用这个 lib 进行 bcrypt:https ://npmjs.org/package/bcrypt这与承诺不兼容,所以我使用“promisify”以下签名:比较(密码,crypted_pa​​ssword,回调)。

所以这是我的代码:

var compare = Promise.promisify(bcrypt.compare);

User.findByEmail(email)   
    .then(compare()) <--- here is the problem

这是我的 findByEmail 方法:

User.prototype.findByEmail = function(email) {
var resolver = Promise.pending();

knex('users')
    .where({'email': email})
    .select()
    .then(function(user) {
        if (_.isEmpty(user)) { resolver.reject('User not found'); }
        resolver.fulfill(user);
    });


return resolver.promise;

}

在这种情况下如何为“比较”方法分配多个值?我错过了承诺的意义吗?

4

2 回答 2

5
.then(compare()) <--- here is the problem

then方法确实需要一个返回另一个承诺 [或纯值] 的函数,因此您需要通过compare而不调用它。如果需要指定参数,请使用包装函数表达式:

User.findByEmail(email)   
    .then(function(user) {
         return compare(/* magic */);
    }).…
于 2014-01-21T23:53:33.537 回答
4

我完全按照 Bergi 所说并为我工作:

this.findByEmail(email)
.then(function(user) {
  return compare(password, user.password);
})
于 2014-01-22T00:19:49.057 回答