【问题标题】:Bluebird promisify multiple arguments蓝鸟承诺多个论点
【发布时间】:2014-02-11 19:55:48
【问题描述】:

我是 Promises 的新手,不知道如何解决这个问题: 我正在做一个身份验证系统,我的第一个电话是检查数据库上的电子邮件。如果用户存在,则根据 bcrypted 密码检查密码...我正在将此库用于 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;

}

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

【问题讨论】:

  • user 变量到底长什么样?
  • 如果没有找到用户,则为空数组,或哈希数组
  • 那么user[0]crypted_password 参数吗?您从代码中的哪里获得password

标签: javascript asynchronous promise q bluebird


【解决方案1】:

我完全按照 Bergi 所说的去做并且为我工作:

this.findByEmail(email)
.then(function(user) {
  return compare(password, user.password);
})

【讨论】:

    【解决方案2】:
    .then(compare()) <--- here is the problem
    

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

    User.findByEmail(email)   
        .then(function(user) {
             return compare(/* magic */);
        }).…
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 2014-11-06
      • 2015-09-06
      • 2015-02-13
      • 1970-01-01
      • 2017-01-19
      相关资源
      最近更新 更多