【发布时间】:2016-02-23 15:33:06
【问题描述】:
我正在使用 NodeJS、bcrypt-nodejs (https://github.com/shaneGirish/bcrypt-nodejs) 和 Bluebird 进行承诺。想出了这段代码,并想知道是否有更好的方法来做同样的事情。我有模块:
var Promise = require("bluebird"),
bcrypt = Promise.promisifyAll(require('bcrypt-nodejs'));
// ....[some othe code here]
Users.prototype.setPassword = function(user) {
return bcrypt.genSaltAsync(10).then(function(result) {
return bcrypt.hashAsync(user.password, result);
});
};
然后我从另一个模块调用users.setPassword,如下所示:
app.post('/api/v1/users/set-password', function(req, res, next) {
users.setPassword(req.body).then(function(result) {
// Store hash in your password DB.
console.log(result[1]);
res.json({
success: true
})
})
.catch(function(err) {
console.log(err);
});
});
它总是以“[错误:没有给出回调函数。]”消息结束,因为bcrypt.hashAsync 似乎需要 4 个参数。原始的、非承诺的 hash 方法只需要 3 个。当我向hashAsync 添加空回调时,它工作正常:
Users.prototype.setPassword = function(user) {
return bcrypt.genSaltAsync(10).then(function(result) {
return bcrypt.hashAsync(user.password, result,function() {});
});
};
有没有更好的方法来做到这一点,而不像上面那样提供空回调?
编辑:
响应Bergi的评论..该功能最终会设置密码,我只是在发布问题时没有那么远。现在已经到这里了,如果有什么不对的地方请告诉我:
Users.prototype.setPassword = function(user) {
return bcrypt.genSaltAsync(10).then(function(result) {
return bcrypt.hashAsync(user.password, result, null);
})
.then(function(result) {
// store in database
console.log("stored in database!");
return result;
});
};
【问题讨论】:
-
我肯定会使用不同的方法名称。
users.setPassword似乎没有设置密码,只是计算给定密码的哈希值。
标签: javascript node.js promise bluebird