spi*_*tus 7 javascript node.js promise bluebird
我正在使用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);
});
};
Run Code Online (Sandbox Code Playgroud)
然后从另一个模块我打电话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);
});
});
Run Code Online (Sandbox Code Playgroud)
它始终以"[错误:没有给出回调函数.]"消息结束,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() {});
});
};
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点,而不提供如上所述的空回调?
编辑:
为了回应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;
});
};
Run Code Online (Sandbox Code Playgroud)
bcrypt.hashAsync似乎需要4个参数.原始的,非promisified哈希方法只需要3.
反之亦然.来自文档:
hash(data, salt, progress, cb)
data
- [必需] - 要加密的数据.salt
- [必需] - 用于散列密码的salt.progress
- 在哈希计算期间调用以表示进度的回调callback
- [必需] - 数据加密后将触发的回调.
原始方法需要4个参数,hashAsync
将取3并返回一个promise.
但是,在您的代码中,您只传递了两个.您不需要传递空函数,参数不是[REQUIRED]意味着您可以传递null
(或任何其他虚假值).bcrypt 会自己创建一个空函数.所以使用
function (data) {
return bcrypt.genSaltAsync(10).then(function(result) {
return bcrypt.hashAsync(data.password, result, null);
});
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6868 次 |
最近记录: |